I everything is good except that when I press A and D and hold it only moves me once, Can anyone help me with this? Here’s my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movement : MonoBehaviour
{
// Start is called before the first frame update
private Rigidbody2D MyRigidBody;
void Start()
{
MyRigidBody = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
MyRigidBody.velocity = Vector2.up * 10;
}
if (Input.GetKeyDown(KeyCode.D))
{
MyRigidBody.velocity = Vector3.right * 10;
}
if (Input.GetKeyDown(KeyCode.A))
{
MyRigidBody.velocity = Vector3.left * 10;
}
}
}
I know my code is kinda messy since I’m new to unity.
because you are testing when the key is down, which is 1 frame…
if you want it to always happen while down you want to test getkey
thanks that solved my issue! The other thing that I need help with is I cant jump while holding A or D.
Look at your code. If you are pressing space and A what do you think happens?
You’re assigning the velocity, which is applied the next time physics is simulated. Since your left an right movement both just override the velocity for jumping, it won’t work when doing one or more both at the same time.
As your code is written, with all inputs pressed down, the last if-statement for A will override everything before it.
You should either use Rigidbody.AddForce
method to push it along, move the rigidbody with Rigidbody.MovePosition
, or build a vector up of the combined forces and apply that once at the end.
how do you build a vector with two combined forces
I dont know how to do that in the code
It’s just Vector3 combinedVector = vectorA + vectorB
.
ok, my difficulty right now is making the 2 vectors.
I was gonna put the x movement on one and the y movement on the other
I reworked my script after watching a bunch of tutorials and used chatgpt to help me as well, thanks for your help spiney! It works very well now.
1 Like