Hi, i try to make my first "game" but i have some isues with coding. I try to make my player jump but he flies
{ Rigidbody2D rb2d; private float moveSpeed = 5; private float jumpSpeed = 7; public const string RIGHT = "D"; public const string LEFT = "A"; public const string UP = "Space"; public const string DOWN = "S"; string buttonPressed; // Start is called before the first frame update void Start() { rb2d = GetComponent();
}
// Update is called once per frame
void Update()
//If Clicked
{
if (Input.GetKey(KeyCode.D))
{
buttonPressed = RIGHT;
}
else if (Input.GetKey(KeyCode.A))
{
buttonPressed = LEFT;
}
else if (Input.GetKey(KeyCode.Space))
{
buttonPressed = UP;
}
else if (Input.GetKey(KeyCode.S))
{
buttonPressed = DOWN;
}
else
{
buttonPressed = null;
}
}
private void FixedUpdate()
//Move
{
if (buttonPressed == RIGHT)
{
rb2d.velocity = new Vector2(moveSpeed, 0);
}
else if (buttonPressed == LEFT)
{
rb2d.velocity = new Vector2(-moveSpeed, 0);
}
else if (buttonPressed == UP)
{
if (buttonPressed == RIGHT)
{
rb2d.velocity = new Vector2(moveSpeed, jumpSpeed);
}
else if (buttonPressed == LEFT)
{
rb2d.velocity = new Vector2(-moveSpeed, jumpSpeed);
}
else
{
GetComponent<Rigidbody2D>().AddForce(new Vector2(0, 2), ForceMode2D.Impulse);
}
}
else if (buttonPressed == DOWN)
{
if (buttonPressed == RIGHT)
{
rb2d.velocity = new Vector2(moveSpeed, -jumpSpeed);
}
else if (buttonPressed == LEFT)
{
rb2d.velocity = new Vector2(-moveSpeed, -jumpSpeed);
}
else
{
rb2d.velocity = new Vector2(0, -jumpSpeed);
}
}
else
{
rb2d.velocity = new Vector2(0, 0);
}
}
}
Answer by Kakal · May 18, 2020 at 10:00 AM
According to your script, the rigidbody only have downward velocity when you press "DOWN" button. When there are no button pressed, you always reset the velocity to (0,0) every FixedUpdate, this will cause your gravity not working to the rigidbody. You should only reset the velocity to (0,0) in the first frame when there are no input.
Your answer
![](https://koobas.hobune.stream/wayback/20220612234519im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Player (Using Player Controller) slow falls when I repeatedly press the jump button while falling., 0 Answers
Collision2D or Trigger2D - Jumping Issue 0 Answers
My jump scripit wont work. i have been tryingtt o make it work for an eternity. please help. 1 Answer
Player Infinitely jumps... 0 Answers
Look rotation viewing vector is zero & diagonal boosting 0 Answers