- Home /
 
move a gameobject to left/right while going up
hi , i have an object which is moving toward up . on the way there are some obstacles . i want to right that when i press left arrow the object move left adn when i press right arrow the object go right ( just want to change the x and keep y as it is going up as much as it is ) , i wrote this but when i press right or left arrow it just move in a shot like lerp is not working . also i want to make it like this that when i press left or right arrow it goes 1 unit to right or 1 unit to left now it's just changing the position to x=1 or x=-1 .
if it is possible take a look at my code and let me know my mistakes and the solution to fix it . thanks a lot .
         float movementSpeed = 2;
     float speed = 1F;
     private float startTime;
     private float journeyLength;
            void Start () 
 {
     startTime = Time.time;
     journeyLength = Vector3.Distance(transform.position, new Vector3 (1f,this.transform.position.y));
 }
         void Update () 
     {
         transform.Translate(Vector3.up * movementSpeed * Time.deltaTime);
 
         float distCovered = (Time.time - startTime) * speed;
         float fracJourney = distCovered / journeyLength;
 
 
         if(Input.GetKeyDown (KeyCode.RightArrow))
         {
             transform.position = Vector3.Lerp(transform.position, new Vector3 (,this.transform.position.y) , fracJourney);
         }
         if(Input.GetKeyDown (KeyCode.LeftArrow))
         {
             transform.position = Vector3.Lerp(transform.position, new Vector3 (-1f,this.transform.position.y) , fracJourney);
             Debug.Log(transform.position.x);
         }
 
     }
 
              Answer by Digital-Phantom · Mar 24, 2015 at 11:39 AM
here is some simple move left/right code -
 void FixedUpdate ()
     {
         float moveHorizontal = Input.GetAxis ("Horizontal");
         Vector3 movement = new Vector3 (moveHorizontal, 0.0f, forwardSpeed);
         GetComponent<Rigidbody>().velocity = movement * speed;
         
     }
 
 
               Its actually part of Unity's 'Space Shooter' tutorial.
http://unity3d.com/earn/tutorials/projects/space-shooter/moving-the-player
Have a look and it will explain it better than I could...lol
:)
Your answer