- Home /
Character jittering when moving and constant back and forth when colliding.
Hi,
I have this code for my 2D character movement along the x axis:
if(Input.GetKey(KeyCode.RightArrow)){
Vector3 position = new Vector3(this.transform.position.x,this.transform.position.y,this.transform.position.z);
position.x = position.x + 0.2f;
this.transform.position = position;
}
if(Input.GetKey(KeyCode.LeftArrow)){
Vector3 position = new Vector3(this.transform.position.x,this.transform.position.y,this.transform.position.z);
position.x = position.x - 0.2f;
this.transform.position = position;
}
if(Input.GetKeyDown(KeyCode.Space)){
if(!isJumping){
isJumping = true;
rigidbody2D.AddForce(new Vector2(0, 20), ForceMode2D.Impulse);
}
}
Works fine for movement, but it is jittery.
I tried using deltaTime to make it smooth, but for some reason it work well then while holding the right arrow, the player slows down after a few seconds.
When my player collides with an object and the arrow is still held down, it jumps back and forth.
What am i doing wrong here?
Thanks for your help in advance.
Answer by keburanuil · Aug 07, 2015 at 03:03 PM
In order to make collisions work, use only the physics methods for the movement. Instead of transform.position, use rigbody2D.position or rigbody2D.MovePosition(). Make sure that the interpolate is turned on in Rigidbody2D -> Interpolate.
Also, you don't need the deltaTime with physics-component.
Your answer
Follow this Question
Related Questions
Using child colliders with rigidbodies/joints in 2D 0 Answers
Problem with method Collider2D.isTouchingLayers() 4 Answers
Find next corner of a 2d pollygon collider 0 Answers
Lerpz ThirdPersonPlayerAnimation bug - running at walking speed 1 Answer
Same script on two gameobjects, only the original(first) one is working 1 Answer