ใช่แล้ว นั้นคือ การจำกัดการเคลื่อนที่ไม่ให้ยานเราออกนอกขอบจอนะครับ
มาเริ่มกันเลยยยย
1. ให้ทำการสร้างยานของเรา โดยการสร้าง Sprite นะครับ (GameObject -> 2D GameObject -> Sprite)
2. จากนั้นก็หารูปยานมาใส่นะครับ
3. ทำการ Add Component Rigidbody2D ให้กับยานเรานะครับ
4. จากนั้นให้ทำการสร้าง C# Script (ShipController.cs)
5. จากนั้นทำการเพิ่ม Script ให้ยานเราเคลื่อนที่ได้
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShipController : MonoBehaviour
{
public float speed = 100;
private Rigidbody2D player;
private Vector3 moveDirection;
void Start()
{
player = GetComponent<Rigidbody2D>();
}
void Update()
{
moveDirection = MovementHandler();
player.velocity = new Vector2 (moveDirection.x, moveDirection.y );
}
private Vector3 MovementHandler()
{
float inputX = Input.GetAxis("Horizontal");
float inputY = Input.GetAxis("Vertical");
Vector3 moveSpeed = new Vector3(inputX, inputY, 0);
moveSpeed = moveSpeed.normalized;
moveSpeed *= (speed * Time.deltaTime);
return moveSpeed;
}
}
7. หลังจากที่เราพอมองเห็นภาพแล้ว ก็ทำการเพิ่ม Script เข้าไปในส่วนของ Update()
// Screen Offset
public Vector2 screenOffsetX;
public Vector2 screenOffsetY;
// Limit movement
// ตรวจจับตำแหน่งของยานเรา บน Screen จะได้ค่า ระหว่าง 0.0 - 1.0
Vector3 pos = Camera.main.WorldToViewportPoint(player.transform.position);
// จำกัดการเคลื่อนที่ แนวแกน X
pos.x = Mathf.Clamp(pos.x, screenOffsetX.x, screenOffsetX.y);
// จำกัดการเคลื่อนที่ แนวแกน Y
pos.y = Mathf.Clamp(pos.y, screenOffsetY.x, screenOffsetY.y);
// set ตำแหน่ง player
player.transform.position = Camera.main.ViewportToWorldPoint(pos);