- Home /
Stopping an object immediately
Hi I'm new to making games and I don't know how make an object stop immediately. I already did some research but nothing helped me. Also, do you guys maybe have some advise to make the script's code a bit more clean? Thanks in advance :)
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
if (Input.GetKey(KeyCode.UpArrow))
{
MoveUp();
}
if (Input.GetKey(KeyCode.DownArrow))
{
MoveDown();
}
}
void MoveUp()
{
float y = Input.GetAxisRaw("Horizontal");
float upwardspeed = y + speed;
rb.velocity = new Vector2(0, upwardspeed);
}
void MoveDown()
{
float y = Input.GetAxisRaw("Horizontal");
float downwardspeed = y - speed;
rb.velocity = new Vector2(0, downwardspeed);
}
Comment
Answer by N-8-D-e-v · Sep 05, 2020 at 01:02 PM
Instead of if (Input.GetKeyDown(KeyCode.UpArrow)
, just use if (Input.GetAxisRaw("Vertical") == 1)
[change to -1 for down] and to stop an object just do rb.velocity = new Vector2(0, 0);
or rb.velocity = Vector2.zero1