Search Unity

Moving an object?

Discussion in 'Getting Started' started by Spoonly, Jun 4, 2020.

  1. Spoonly

    Spoonly

    Joined:
    May 5, 2020
    Posts:
    2
    hi! Im trying to code a script to move a sphere. I tried out this script, unity doesn't seem to have any problem with it, however, whenever I run the game the sphere doesn't move in any direction. could someone please help me out here? thank you!
    here's the script

    using UnityEngine;

    public class playermovement2 : MonoBehaviour
    {
    public Rigidbody rb;

    void start ()
    {


    if (Input.GetKey("w"))
    {
    transform.position = new Vector3(0, 1, 0);
    }

    if (Input.GetKey("s"))
    {
    transform.position = new Vector3(0, -1, 0);
    }

    if (Input.GetKey("d"))
    {
    transform.position = new Vector3(1, 0, 0);
    }

    if (Input.GetKey("a"))
    {
    transform.position = new Vector3(-1, 0, 0);
    }



    }
    }
     
  2. jbnlwilliams1

    jbnlwilliams1

    Joined:
    May 21, 2019
    Posts:
    267
    1. when you post code, please use code tags.
    2. Your code is in the start method, so it only runs once. So unless you hit one of the movement keys at precisely the right time it will never see it.
    3. Move your code into the update method.
     
  3. jbnlwilliams1

    jbnlwilliams1

    Joined:
    May 21, 2019
    Posts:
    267
    Code (CSharp):
    1. public class MoveMe : MonoBehaviour
    2. {
    3.     public Rigidbody rb;
    4.  
    5.     void start()
    6.     {
    7.  
    8.     }
    9.        
    10.  
    11.     void Update()
    12.     {
    13.             if (Input.GetKey("w"))
    14.             {
    15.                 transform.position = new Vector3(0, 1, 0);
    16.             }
    17.  
    18.             if (Input.GetKey("s"))
    19.             {
    20.                 transform.position = new Vector3(0, -1, 0);
    21.             }
    22.  
    23.             if (Input.GetKey("d"))
    24.             {
    25.                 transform.position = new Vector3(1, 0, 0);
    26.             }
    27.  
    28.             if (Input.GetKey("a"))
    29.             {
    30.                 transform.position = new Vector3(-1, 0, 0);
    31.             }
    32.     }
    33.  
    34.  
    35.  
    36. }
     
    JoeStrout likes this.
  4. Spoonly

    Spoonly

    Joined:
    May 5, 2020
    Posts:
    2
    thank you so much, it actually works now! Apologies for not using the code tags, I'm new so I didn't realize that I had to do that, thanks again!
     
    DauntlessVerbosity and JoeStrout like this.
  5. jbnlwilliams1

    jbnlwilliams1

    Joined:
    May 21, 2019
    Posts:
    267