Question by
boatkay · Aug 12, 2016 at 05:37 AM ·
inputmanagerrigidbody.velocityrigidbody.moveposition
How to move an rigidbody left and right as it is moving up
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));
}
}
Comment
Answer by flatalex123 · Aug 12, 2016 at 09:06 AM
Try and use (not sure if this will work)
transform.position += new Vector3(0, 0, 0);
change the 0s to what you want first one is x then y then z. I think
eg first 0 to 5