This code causes my player to teleport upward and then slowly fall back down when I hit the spacebar. I haven’t yet added movement to the left, but walking to the right works fine.
public class PlayerMovement : MonoBehaviour
{
public Rigidbody2D rb;
public float jump;
public float walk;
public bool tf = false;
public Vector3 d;
public Vector3 space;
public Vector3 a;
// Update is called once per frame
void Update()
{
if (Input.GetKey("d"))
{
d = new Vector3(walk, 0, 0);
}
else
{
d = new Vector3(0, 0, 0);
}
if (Input.GetKeyDown("space"))
{
tf = true;
}
else
{
tf = false;
}
}
void OnCollisionStay2D(Collision2D collisionInfo)
{
if (tf == true)
{
space = new Vector3(0, jump, 0);
}
else
{
space = new Vector3(0, 0, 0);
}
rb.velocity = d + space + a;
}
}
oh yeah, that’s probably a pretty important thing to include. I’m just setting up basic movement controls. What’s included in the code I posted is space to jump and d to move right
But jumping isn’t working right. Instead of giving me upwards velocity, it teleports me up a certain amount that is directly related to the value of jump, then I slowly fall down
I think it’s because your jump code produces either one of two outcomes: y velocity will be jump, or it will be 0. That’s gonna cause it to suddenly jump up and then suddenly stop in mid-air.
I don’t think you need the OnCollisionStay2D function. I would guess that you have that in order to tell when the player is on the ground, but IMO I think a raycast is better for that.
Maybe create a function called IsGrounded() that returns a bool depending on whether the player is on the ground (as determined by a raycast)
then, in Update(), check if IsGrounded() == true && Input.GetKeyDown(“space”), and if it is, call another function called Jump() which does rb.velocity = new Vector3(rb.velocity.x, jump, rb.velocity.z)
If I run that, it doesn’t work because I don’t have a character controller attached, but it doesn’t allow me to add a character controller because I’m in 2D. Am I using the command wrong? This is my first time working with functions, so I’m a little in over my head
public bool Grounded()
{
if (controller.isGrounded)
{
Debug.Log("Grounded");
return true;
}
else
{
Debug.Log("Not Grounded");
return false;
}
}
and then I am calling the function in the update with this line
If controllers don’t work in 2D then I suppose you’ll have to use some kind of 2D raycast or 2D collider (probably raycast is better). Unity - Scripting API: Physics2D.Raycast