107 lines
3.1 KiB
C#
107 lines
3.1 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
public class SnakeController : MonoBehaviour
|
|
{
|
|
public float movingInterval = 0.2f;
|
|
public Vector2 curDirection = Vector3.right;
|
|
public List<Vector2> tail = new List<Vector2>();
|
|
public List<Transform> snakePieces = new List<Transform>();
|
|
public GameObject snakePiecePrefab;
|
|
public int startingLength = 3;
|
|
|
|
public Vector2 fieldSize= new Vector2(160,90);
|
|
float moveTimer;
|
|
|
|
float topEdge => transform.position.y + fieldSize.y /2f;
|
|
float botEdge => transform.position.y -fieldSize.y /2f;
|
|
float leftEdge =>transform.position.x-fieldSize.x/2f;
|
|
float rightEdge => transform.position.x + fieldSize.x/2f;
|
|
|
|
|
|
void Start(){
|
|
tail = new List<Vector2>();
|
|
for(int i=0; i < startingLength; i++){
|
|
Vector3 pos = (Vector2)transform.position-(Vector2.right * i);
|
|
tail.Add(pos);
|
|
GameObject newPiece = Instantiate(snakePiecePrefab,pos, Quaternion.identity );
|
|
snakePieces.Add(newPiece.transform);
|
|
}
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
Move();
|
|
|
|
if(Input.GetKeyDown(KeyCode.RightArrow)){
|
|
ChangeDir(Vector2.right);
|
|
}else if(Input.GetKeyDown(KeyCode.LeftArrow)){
|
|
ChangeDir(-Vector2.right);
|
|
}else if(Input.GetKeyDown(KeyCode.UpArrow)){
|
|
ChangeDir(Vector2.up);
|
|
}else if(Input.GetKeyDown(KeyCode.DownArrow)){
|
|
ChangeDir(-Vector2.up);
|
|
}
|
|
|
|
if(Input.GetKeyDown(KeyCode.Space)){
|
|
queueNewPiece=true;
|
|
}
|
|
}
|
|
|
|
void ChangeDir(Vector2 newDir){
|
|
if(curDirection == -newDir){
|
|
return;
|
|
}
|
|
|
|
curDirection = newDir;
|
|
}
|
|
|
|
bool queueNewPiece = false;
|
|
|
|
void Move(){
|
|
if(moveTimer > 0){
|
|
moveTimer-=Time.deltaTime;
|
|
}else{
|
|
moveTimer = movingInterval;
|
|
Vector2 curPosition = tail[0];
|
|
Vector2 lastPosition = tail[tail.Count-1];
|
|
|
|
for(int i=tail.Count-1; i>0; i--){
|
|
tail[i] = tail[i-1];
|
|
snakePieces[i].position = tail[i];
|
|
}
|
|
|
|
if(queueNewPiece){
|
|
tail.Add(lastPosition);
|
|
GameObject newPiece = Instantiate(snakePiecePrefab,lastPosition, Quaternion.identity );
|
|
snakePieces.Add(newPiece.transform);
|
|
|
|
queueNewPiece=false;
|
|
}
|
|
|
|
tail[0] = curPosition + curDirection;
|
|
|
|
if(tail[0].x > rightEdge){
|
|
tail[0]= new Vector2(leftEdge,tail[0].y);
|
|
}else if(tail[0].x <leftEdge){
|
|
tail[0]= new Vector2(rightEdge,tail[0].y);
|
|
}
|
|
|
|
|
|
|
|
if(tail[0].y > topEdge){
|
|
tail[0] = new Vector2(tail[0].x, botEdge);
|
|
}else if(tail[0].y < botEdge){
|
|
tail[0] = new Vector2(tail[0].x, topEdge);
|
|
}
|
|
snakePieces[0].position = tail[0];
|
|
}
|
|
}
|
|
|
|
private void OnDrawGizmos() {
|
|
Gizmos.DrawWireCube(transform.position, new Vector3(fieldSize.x,fieldSize.y));
|
|
}
|
|
|
|
}
|