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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Need help to move my object. (easy to fix, just hard for me XD )

Discussion in 'Scripting' started by MortisFillius, Dec 12, 2014.

  1. MortisFillius

    MortisFillius

    Joined:
    Feb 10, 2014
    Posts:
    14
    Hello, i want to make a game that features a spaceship that teleports to the sides where you need to dodge different objects.

    But i experienced troubles with the movement. I want it to be so that while you hold the arrow keys to the left or right the spaceship teleports and stays at that position untill you let go of the arrow key and then it returns to the middle.
    But i can't find a way to do that. The script i have right now makes the spaceship teleport back instantly after the spaceship takes it position to the right or left.

    this is my code right now.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class MovementUP : MonoBehaviour {
    5.     new public GameObject Rocket;
    6.     new Vector3 StartPos = new Vector3 (0, -3, 0);
    7.     new Vector3 RightPos = new Vector3 (6,-3,0);
    8.     new Vector3 LeftPos = new Vector3 (-6,-3,0);
    9.  
    10.     // Use this for initialization
    11.     void Start () {
    12.    
    13.         Rocket.transform.position = StartPos;
    14.  
    15.     }
    16.  
    17.     // Update is called once per frame
    18.     void Update () {
    19.  
    20.  
    21.    
    22.                 if (Input.GetKeyDown (KeyCode.D)) {
    23.                         Rocket.transform.position = RightPos;
    24.  
    25.                        
    26.                 } else if (Input.GetKeyDown (KeyCode.A)) {
    27.                         Rocket.transform.position = LeftPos;
    28.        
    29.                 }
    30.  
    31.          else if ((Input.GetKeyDown(KeyCode.A) == false ) & (Input.GetKeyDown(KeyCode.D) == false))
    32.         {
    33.             Rocket.transform.position = new Vector3 (0,-3,0);
    34.                 }
    35.                
    36.     }
    37. }
    So what can i do to make it stay to the sides untill i let go of the key?
     
  2. Megolas

    Megolas

    Joined:
    Apr 6, 2013
    Posts:
    25
    Use Input.GetKey - Input.GetKeyDown returns true if the button has been pressed only during the last frame.
    So, as an example: if(Input.GetKey(KeyCode.A))
     
  3. MortisFillius

    MortisFillius

    Joined:
    Feb 10, 2014
    Posts:
    14
    Thank you very much :)