Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Moving 2d objects with WASD/Arrow keys at a constand speed (c#)

Discussion in 'Scripting' started by nedas60, Jul 15, 2016.

  1. nedas60

    nedas60

    Joined:
    Jul 14, 2016
    Posts:
    2
    I looked everywhere to see if I can find this but I couldn't. So could anyone help me make a constant movement script and explain how it is done? With a public float speed? If possible stop it from passing through hitboxes. I am trying to make a puzzle-ish game. No gravity. If needed I could use components. I am kinda new to unity coding so I have a lot to learn.
     
  2. jimroberts

    jimroberts

    Joined:
    Sep 4, 2014
    Posts:
    560
    Generally you have a direction vector that you multiply by your speed value (Example Below). Collision detection is a bit more involved. I would suggest following some of the Official Unity Tutorials. If you aren't understanding something please feel free to come back and ask for help.

    Calculate movement direction vector:
    Code (csharp):
    1. public Vector3 CalculateDirection()
    2. {
    3.    Vector3 direction = Vector3.zero;
    4.    if (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W))
    5.    {
    6.      direction.y += 1.0f;
    7.    }
    8.    if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A))
    9.    {
    10.      direction.x -= 1.0f;
    11.    }
    12.    if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S))
    13.    {
    14.      direction.y -= 1.0f;
    15.    }
    16.    if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D))
    17.    {
    18.      direction.x += 1.0f;
    19.    }
    20.    return direction.normalized;
    21. }
    Move the object:
    Code (csharp):
    1. public float MovementSpeed;
    2.  
    3. void Update()
    4. {
    5.    Vector3 direction = CalculateDirection();
    6.    transform.Translate(direction * MovementSpeed * Time.deltaTime);
    7. }
    Alternatively:
    Code (csharp):
    1. public float MovementSpeed;
    2. public Vector3 MoveDirection;
    3.  
    4. void Update()
    5. {
    6.    MoveDirection = CalculateDirection();
    7. }
    8.  
    9. void FixedUpdate()
    10. {
    11.    transform.Translate(direction * MovementSpeed);
    12. }
     
    Last edited: Jul 15, 2016
    nedas60 likes this.
  3. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    ok, few problems here... firstly, fixedupdate is used for physics based movement, if you try to access "input" from fixedupdate you run the risk of missing input thanks to fixedupdate not being called every frame. It shouldn't be used just because you want "fixed rate movement"; that's one of the reasons for Time.deltaTime existing.
    secondly, the whole point of unity's input manager existing is to stop the need for hardcoding the keys into the scripts allowing for user remapped keys and making it simple make changes later on, it also reduces the repetitive code.

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class Test : MonoBehaviour
    6. {
    7.     public float speed;
    8.    
    9.     void Update ()
    10.     {
    11.         // GetAxisRaw is unsmoothed input -1, 0, 1
    12.         float v = Input.GetAxisRaw("Vertical");
    13.         float h = Input.GetAxisRaw("Horizontal");
    14.  
    15.         // normalize so going diagonally doesn't speed things up
    16.         Vector3 direction = new Vector3(h, v, 0f).normalized;
    17.  
    18.         // translate
    19.         transform.Translate(direction * speed * Time.deltaTime);
    20.     }
    21. }
    22.  
     
    blainelight, nedas60 and jimroberts like this.
  4. jimroberts

    jimroberts

    Joined:
    Sep 4, 2014
    Posts:
    560
    In my script I have the direction stored and updated with Update so I totally missed the fact I put it in FixedUpdate when posting it here. That's what I get for coding at 4 AM. Some people don't like the built-in input manager which is why I suggested the other way. Anyway my reply is fixed.
     
    LeftyRighty likes this.
  5. nedas60

    nedas60

    Joined:
    Jul 14, 2016
    Posts:
    2
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class Test : MonoBehaviour
    6. {
    7.     public float speed;
    8.  
    9.     void Update ()
    10.     {
    11.         // GetAxisRaw is unsmoothed input -1, 0, 1
    12.         float v = Input.GetAxisRaw("Vertical");
    13.         float h = Input.GetAxisRaw("Horizontal");
    14.  
    15.         // normalize so going diagonally doesn't speed things up
    16.         Vector3 direction = new Vector3(h, v, 0f).normalized;
    17.  
    18.         // translate
    19.         transform.Translate(direction * speed * Time.deltaTime);
    20.     }
    21. }
    22.  
    [/QUOTE]

    Doesn't really move. Am I missing something?
    Anyway thanks for the help:D

    Edit: I forgot the speed.. It works!
     
    Last edited: Jul 15, 2016
  6. blainelight

    blainelight

    Joined:
    Jul 6, 2018
    Posts:
    1
    This code is simple and works really well. Thanks for your help!
     
  7. cuber7

    cuber7

    Joined:
    Apr 24, 2021
    Posts:
    1
    does any one know what this means and how to fix it?
    Assets\move.cs(16,42): error CS1026: ) expected
     
  8. Realspawn1

    Realspawn1

    Joined:
    Jun 8, 2015
    Posts:
    126
    It means somewhere in your code a ) is needed to close a line that was openened with a (
     
  9. jujuthetford

    jujuthetford

    Joined:
    May 30, 2021
    Posts:
    1
    I am using unity 2020.3.9f1. How do I move a circle? I tried using jimroberts example but nothing happened when I pressed WASD or the arrow keys. It wasn't moving the circle, what else can work?