I tried to make a simple movement script partially following a tutorial, and somehow it works different from what it showed me in the tutorial. I used the AddForce function to make the character ascend and descend evenly, but it simply teleports upwards and then descends as it should be. I tried changing the Force2D.Impulse to Force2D.Force back and forth, I played for like 20 minutes with all the inspector values, and no matter what I change, it still does the same thing. I know it’s a incredibly simple script and it shouldn’t be a problem usually, but I can’t find any answers for this particular problem, and so far I’ve tried any solutions from other questions and still nothing.
public class PlayerMovement : MonoBehaviour
{
// Start is called before the first frame update
public float movementSpeed = 10f;
public GameObject CeilingCheck;
public GameObject GroundCheck;
public float jumpForce = 20f;
public bool isGrounded;
void Start()
{
}
// Update is called once per frame
void Update()
{
Rigidbody2D rb = gameObject.GetComponent<Rigidbody2D>();
rb.velocity = new Vector2(Input.GetAxis("Horizontal") * Time.deltaTime * movementSpeed * 100, 0f);
if ((isGrounded == true) && (Input.GetKeyDown("w")))
{
rb.AddForce(new Vector2(0f, jumpForce), ForceMode2D.Impulse);
}
}
}
The horizontal movement works pretty much fine, i’m gonna polish it later, maybe try and play with the advices you gave me and try to make it work. But on the y axis the character teleports up, and then descents as it should.
public class GroundCheck : MonoBehaviour
{
GameObject Player;
// Start is called before the first frame update
void Start()
{
Player = GameObject.Find("Player");
}
// Update is called once per frame
void Update()
{
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.tag == "Ground")
Player.GetComponent<PlayerMovement>().isGrounded = true;
Debug.Log("Collisioned with Ground");
}
private void OnCollisionExit2D(Collision2D collision)
{
if (collision.collider.tag == "Ground")
Player.GetComponent<PlayerMovement>().isGrounded = false;
Debug.Log("Collisioned with Ground");
}
}
The groundcheck works fine, but maybe it’ll help troubleshoot the problem.
The problem is horizontal movement. Because you’re setting the velocity of y vector as 0 in rb.velocity = new Vector2(Input.GetAxis("Horizontal") * Time.deltaTime * movementSpeed * 100, 0f);
leave the jump part as it is and use this: rb.velocity = new Vector2(Input.GetAxis("Horizontal") * Time.deltaTime * movementSpeed * 100f, rb.velocity.y);
so, it’ll retain the original vertical velocity, instead of just setting vertical velocity to 0;
also you should type “f” after float values