除了player以外,建立一个abstract class character 隶属于player
character代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class Character : MonoBehaviour {
[SerializeField]
private float speed;
protected Vector2 direction;
void Start () {
}
protected virtual void Update () {
Move();
}
public void Move()
{
transform.Translate(direction * speed * Time.deltaTime);
}
}
player修改后代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : Character {
[SerializeField]
private float speed;
//public后,可在外面屬性欄賦值,private不可,會隱藏該屬性欄,而加了[SerializeField]后,即可以private的狀態賦值
void Start () {
}
protected override void Update () {
GetInput();
base.Update();
}
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;
}
}
}