I have a game object with a rigidbody. It is like a space which is continuously moving up and then when the player presses the left arrow, I want the object to shift left to avoid obstacles.
I have been trying to use rigidbody.moveposition to do that but when ever i press the left button, the spaceship moves to left and stop moving up and then also disappear from the screen. How can I fix this so that when the user presses left, the spaceship moves smoothly to the left as it keeps moving up. This is the code that I used:
public class PlayerController : MonoBehaviour {
Rigidbody2D rb;
public float gameSpeed;
bool moveLeft;
// Use this for initialization
void Start ()
{
rb = GetComponent <Rigidbody2D> ();
}
// Update is called once per frame
void Update ()
{
if (Input.GetKeyUp (KeyCode.LeftArrow))
{
moveLeft = true;
}
}
void FixedUpdate ()
{
MovePlayer ();
}
void MovePlayer ()
{
rb.velocity = (new Vector2 (0, 1f)) * gameSpeed; //Move player continuosly up
//Move Player to left and right as player keeps moving up.
if (moveLeft)
{
rb.MovePosition (new Vector2 ((transform.position.x - 1.4f), transform.position.y));
}
}