- Home /
snake problem
I'm trying to snake with unity. I have a problem with the creation of the body. As you know every time you eat the food the body of the snake gets longer. I make an array of GameObject and add a piece every time. This is my code. The problem is that I do not know how to add an object to an array of objects. I've tried using the Add and push but does not work. In addition, each piece of the body should follow the previous positions that the problem should have a 1 second delay otherwise change position immediately.
#pragma strict
//VARIABILI PUBLIC
public var direction : String = 'Right';
public var currentDirection : String;
public var input;
public var cubo : GameObject[];
public var food : GameObject;
var Snake : GameObject;
function Start () {
var position: Vector3 = Vector3(Random.Range(0, 10.0), Random.Range(0, 5.0), 0);
Instantiate(food, position, Quaternion.identity);
}
function Update () {
if(Input.GetMouseButtonDown(0))
{
//Debug.Log("premuto");
var agg = Instantiate(Snake, new Vector3(cubo[0].transform.position.x, cubo[0].transform.position.y , cubo[0].transform.position.z), Quaternion.identity);
//cubo.Add(agg);
}
var horizontal = Input.GetAxis("Horizontal");
var vertical = Input.GetAxis("Vertical");
if(horizontal >0 && currentDirection != 'Left')
{
direction = 'Right';
}
if(horizontal < 0 && currentDirection != 'Right')
{
direction = 'Left';
}
if(vertical < 0 && currentDirection != 'Up')
{
direction = 'Down';
}
if(vertical > 0 && currentDirection != 'Down')
{
direction = 'Up';
}
move();
}
function move(){
if(direction == 'Right'){
cubo[0].transform.Translate(0.03,0,0);
currentDirection = direction;
draw();
}
if(direction == 'Left'){
cubo[0].transform.Translate(-0.03,0,0);
currentDirection = direction;
draw();
}
if(direction == 'Up'){
cubo[0].transform.Translate(0,0.03,0);
currentDirection = direction;
draw();
}
if(direction == 'Down'){
cubo[0].transform.Translate(0,-0.03,0);
currentDirection = direction;
draw();
}
}
function draw()
{
for(var i =0; i<=cubo.Length; i++){
var prev = cubo[0].transform.position;
cubo[i+1].transform.position= cubo[i].transform.position;
}
}
Comment