Search code examples
unity-game-engineunityscript

Unity won't accept my float (JS, 2d)


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 ;)


Solution

  • 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);
        }
    }