Game Development

เขียนเกม Unity 3D การทำ Mouse Movement เคลื่อนไหวตัวละคร

บทเรียนการพัฒนาเกมด้วย Unity 3D กับการเคลื่อนไหวตัวละครด้วยเคลื่อน Mouse ไปมาซ้ายขวา สำหรับผู้เริ่มต้นพัฒนาเกมด้วย Unity และภาษา C# ตัวอย่างเช่น เกมยิงต่างๆ

บทเรียนก่อนหน้านี้: https://www.daydev.com/category/developer/s11-game-development/unity-3d

เปิดโปรเจ็ค Unity ขึ้นมาเลยครับ เทคนิคนี้ไม่ยากเลยแม้แต่น้อย สร้าง Player ลงไปใน Scene View กำหนด Physics ทั้งส่วนของ Character Controller, Capsule หรือ Box Collider และ Rigidbody แบบไม่มี Gravity ครับ ตามตัวอย่าง

unity-3d-mouse-movement-1

ตั้งค่า Inspector ตามตัวอย่างก็ได้ครับ

unity-3d-mouse-movement-2

สร้างไฟล์ Player.cs ขึ้นมา กำหนดตัวแปรต่อไปนี้

private Vector3 targetPos;
public float speed = 2.0f;

กำหนด targetPos เป็นตัวแปรมารับค่า Vector3 หรือตัว GameObject ตัวละครของเราครับ พร้อมตัวแปร speed มารับค่าความเร็วในตอบสนองและเคลื่อนไหวไปมา ทำการ init ค่าใน เมธอด Start();

void Start () {
   targetPos = transform.position; 
}

ต่อจากนั้นทำการควบคุมตัวละครต่อที่ เมธอด Update

void Update () {
		float distance = transform.position.z - Camera.main.transform.position.z;
		targetPos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, distance);
		targetPos = Camera.main.ScreenToWorldPoint(targetPos);
		
		Vector3 followXonly = new Vector3(targetPos.x, transform.position.y, transform.position.z);
		transform.position = Vector3.Lerp (transform.position, followXonly, speed * Time.deltaTime);
	}

สังเกตที่ส่วนนี้ครับ

Vector3 followXonly = new Vector3(targetPos.x, transform.position.y, transform.position.z);

กำหนดในตัวอย่างคือให้ followXonly คือให้ตัวละครของเราเคลื่อนไหวตาม Mouse แค่แกน x นั่นคือซ้าย และขวา เท่านั้นครับ เมื่อเสร็จก็ลองทดสอบดู

unity-3d-mouse-movement-3

ตัวอย่างก็ดูด้านล่างฮะ

เป็นไงครับ ง่ายใช่ไหมลองเอาไปปรับใช้กับเกมของตัวเองกันนะครับ เทคนิคสั้นมากๆ

Asst. Prof. Banyapon Poolsawas

อาจารย์ประจำสาขาวิชาการออกแบบเชิงโต้ตอบ และการพัฒนาเกม วิทยาลัยครีเอทีฟดีไซน์ & เอ็นเตอร์เทนเมนต์เทคโนโลยี มหาวิทยาลัยธุรกิจบัณฑิตย์ ผู้ก่อตั้ง บริษัท Daydev Co., Ltd, (เดย์เดฟ จำกัด)

Related Articles

Back to top button
Game & Mobile Development AR VR XR
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Adblock Detected

เราตรวจพบว่าคุณใช้ Adblock บนบราวเซอร์ของคุณ,กรุณาปิดระบบ Adblock ก่อนเข้าอ่าน Content ของเรานะครับ, ถือว่าช่วยเหลือกัน