0
votes

I am making a top down 'atari' type game and ive been having a little trouble recently, I am using transform.position to change my coordinate on the screen but using GetKey moves a little too fast, so I tried to use a float to slow down the progression and its not moving at all now... here is my code

 #pragma strict
 var xCoor = 0;
 var yCoor = 0;    


 function Start () {
 }

 function Update () {    

     if(Input.GetKey (KeyCode.D))
         xCoor += 0.5;
         transform.position = Vector2(xCoor,yCoor);
     if(Input.GetKey (KeyCode.W))
         yCoor += 0.5;
         transform.position = Vector2(xCoor,yCoor);
     if(Input.GetKey (KeyCode.A))
         xCoor += -0.5;
         transform.position = Vector2(xCoor,yCoor);
     if(Input.GetKey (KeyCode.S))
         yCoor += -0.5;
         transform.position = Vector2(xCoor,yCoor);
 }

As you can probably tell im new to Unity so if there is a better way, please share! Thank you ;)

1
Probably not related, but you're missing braces all over the if's. Should be something like: if(Input.GetKey (KeyCode.D)) { xCoor += 0.5; transform.position = Vector2(xCoor,yCoor); } - Anderson Pimentel
You can do it either way, this was a quick code I was pulling together, I understand that brackets are good practice - Daniel Bickerdike
@DanielBickerdike your code works, but almost by accident lol. Since you don't have any brackets, you're always setting transform.position (regardless of the conditional). - Carlos Rodriguez

1 Answers

2
votes

I'm not sure, but I believe that your xCoor is of type int. So when you try to add the float to it, it doesn't change.

Change the definition of xCoor and yCoor to be 0.0 instead of 0, and see if that works.

#pragma strict
var xCoor = 0.0;
var yCoor = 0.0;   

Also, as has been pointed out in the comments, you really should put some braces after the if statements, so that you get unwanted results.

function Update () {    
    if(Input.GetKey (KeyCode.D)) {
        xCoor += 0.5;
        transform.position = Vector2(xCoor,yCoor);
    }

    if(Input.GetKey (KeyCode.W)) {
        yCoor += 0.5;
        transform.position = Vector2(xCoor,yCoor);
    }

    if(Input.GetKey (KeyCode.A)) {
        xCoor += -0.5;
        transform.position = Vector2(xCoor,yCoor);
    }

    if(Input.GetKey (KeyCode.S)) {
        yCoor += -0.5;
        transform.position = Vector2(xCoor,yCoor);
    }
}