For a class I’m taking, I have to make a platformer, and plan on making my character jump when the spacebar is hit. For some reason, this isn’t working.
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
public Rigidbody2D rb;
[SerializeField] private float speed = 2f;
[SerializeField] private float force = 10f;
private void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.RightArrow))
{
transform.position += new Vector3(speed * Time.deltaTime, 0f, 0f);
}
if (Input.GetKey(KeyCode.LeftArrow))
{
transform.position -= new Vector3(speed * Time.deltaTime, 0f, 0f);
}
if (Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(Vector2.up * force, ForceMode2D.Impulse);
}
}
}
Hello, in this case your transform.position is overriding the rb.AddForce
It is not recommended to modify the transform directly while using a Rigidbody as this will cause issues like unpredictable movement or GameObjects passing through and into each other.
You can refer to our documentation on how it works here and more info on Dynamic or Kinematic Body Types to suit your gameplay needs
You are misusing the physics system, bypassing it with direct transform manipulation. Don’t do that.
With Physics (or Physics2D), never manipulate the Transform directly. If you manipulate the Transform directly, you are bypassing the physics system and you can reasonably expect glitching and missed collisions and other physics mayhem.
This means you may not change transform.position, transform.rotation, you may not call transform.Translate(), transform.Rotate() or other such methods, and also transform.localScale is off limits. You also cannot set rigidbody.position or rigidbody.rotation directly. These ALL bypass physics.
Always use the .MovePosition() and .MoveRotation() methods on the Rigidbody (or Rigidbody2D) instance in order to move or rotate things. Doing this keeps the physics system informed about what is going on.
How would I edit the code to include .MovePosition to the RigidBody2D so it works properly? I’m fairly new to Unity, so I’m a bit lost on these subjects.
Definitely start with the API documentation itself, there’s probably example code.
Otherwise tutorials for how to use MovePosition do exist
If you wanna go at it yourself, break apart line 22 (and line 26) so that it extracts the value, adds the movement, then assigns the value back to transform.
Finally replace that third step: instead of assigning it to transform, call .MovePosition() on it.