snake/Assets/Scenes/Player1.cs

48 lines
1.3 KiB
C#

using UnityEngine;
public class Player1 : MonoBehaviour
{
enum Direction {
Left,
Up,
Right,
Down
}
public Vector2Int direction = Vector2Int.right;
private Vector2Int input;
// Start is called before the first frame update
void Start() {
direction = Vector2Int.right;
}
// Update is called once per frame
void Update() {
if (direction.x != 0f) {
if (Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow)) {
input = Vector2Int.up;
} else if (Input.GetKeyDown(KeyCode.S) || Input.GetKeyDown(KeyCode.DownArrow)) {
input = Vector2Int.down;
}
} else if (direction.y != 0f) {
if (Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.RightArrow)) {
input = Vector2Int.right;
} else if (Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.LeftArrow)) {
input = Vector2Int.left;
}
}
}
void FixedUpdate() {
if (input != Vector2Int.zero) {
direction = input;
}
int x = Mathf.RoundToInt(transform.position.x) + direction.x;
int y = Mathf.RoundToInt(transform.position.y) + direction.y;
transform.position = new Vector2(x, y);
}
}