- Home /
How do I move player/object-2D up and down?
I am making a Ping Pong test game where two people can play (arrowDown + arrowUP and w + s) but i can't get it to work. I made this by "translating" it from another script in UnityScript.
How can I get the player object to move up or down?
[RequireComponent(typeof(Rigidbody2D))]
[RequireComponent(typeof(BoxCollider2D))]
public class PlayerControl : MonoBehaviour {
//Var for which key to press to move
public KeyCode moveUp;
public KeyCode moveDown;
//The speed of the player
public int speed = 12;
// Update is called once per frame
void Update () {
if (Input.GetKey(moveUp))
{
rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.y, speed);
}
else if (Input.GetKey(moveDown))
{
rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x, speed *-1);
}
else
{
rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.y, 0);
}
rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x, 0);
}
}
Answer by Maui-M · Feb 06, 2014 at 09:48 PM
Line 28 is always being called so its overwriting any other velocity you set.
rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x, 0);
Since you only want it going up and down you only want to change the y value of the velocity.
// Update is called once per frame
void Update () {
if (Input.GetKey(moveUp))
{
rigidbody2D.velocity = new Vector2(0, speed);
}
else if (Input.GetKey(moveDown))
{
rigidbody2D.velocity = new Vector2(0, speed *-1);
}
else
{
rigidbody2D.velocity = new Vector2(0, 0);
}
}
So how would I fix this? I tried removing it but the object/player acts weird and moves up and right.
just put all thies in seprate conditions like
if (Input.Get$$anonymous$$ey(moveUp))
{
rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.y, speed);
}
else
{
rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.y, 0);
}
if (Input.Get$$anonymous$$ey(moveDown))
{
rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x, speed *-1);
}
else
{
rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x, 0);
}
That is even worse, I need someway to not reset rigidbody2D.velocity all the time. Like in Unityscript where you type rigidbody2D.velocity.y/x
Your answer
Follow this Question
Related Questions
2D Character suddenly stops moving for no given reason 1 Answer
Simple Rigidbody2D movement and jump 0 Answers
Simple moving ball script 1 Answer
How to go about having two seperate Game Objects follow eachother? 1 Answer
in 2d game, while draging and dropping object its movement very slow , it can't move smoothly ? 0 Answers