这是做出人物上下左右,根据你赋值的速度移动的代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour {
[SerializeField]
private float speed;
//public后,可在外面屬性欄賦值,private不可,會隱藏該屬性欄,而加了[SerializeField]后,即可以private的狀態賦值
private Vector2 direction;
void Start () {
}
void Update () {
GetInput();
Move();
}
public void Move()
{
transform.Translate(direction * speed * Time.deltaTime);//一直向右移動(會出屏幕)和上面的Move();呼應
}
private void GetInput()
{
direction = Vector2.zero;
if(Input.GetKey(KeyCode.W))
{
direction += Vector2.up;
}
if (Input.GetKey(KeyCode.A))
{
direction += Vector2.left;
}
if (Input.GetKey(KeyCode.S))
{
direction += Vector2.down;
}
if (Input.GetKey(KeyCode.D))
{
direction += Vector2.right;
}
}
}