Best way to move an object smoothly
Hello I am trying to make a simple space mobile game. and I want my spaceship to continuously move up and can swipe left or right to move it to either the left or right to avoid obstacles. Right now I am using rigidbody2d.velocity to continuously move the spaceship up. But it doesn't seem smooth and realistic at all. There seem to be so much breaking in the movement. So I was wondering what would be the best possible way to move the object smoothly. I would be glad if someone could post some code of how I can move the object more efficiently and smoothly. This is my code for moving the object.
public class PlayerController : MonoBehaviour {
Rigidbody2D rb;
public float gameSpeed;
// Use this for initialization
void Start ()
{
rb = GetComponent <Rigidbody2D> ();
}
void FixedUpdate ()
{
MovePlayer ();
}
void MovePlayer ()
{
rb.velocity = (new Vector2 (rb.velocity.x, 1f)) * gameSpeed;
}
}
Answer by Rob2309 · Aug 09, 2016 at 12:54 AM
If you don't need any physics, you could just do the following:
public float verticalSpeed;
void Update()
{
transform.position += Vector3.up * verticalSpeed * Time.deltaTime;
}
If you, however, need some physics, consider using RigidBody.AddForce(...) (Documentation here)
@Rob2309 what do you mean by if I would not need physics. I would be needing collider and would also liked to move the player object from left to right. Do you think that inculude physics?
Answer by MelvMay · Aug 09, 2016 at 08:44 AM
The physics system only updates the positions at the fixed-update interval, not each frame as that would be expensive and inconsistent.
You can however ask the Rigidbody2D to update the Transform position each frame using interpolation from the old position to the new (current) one:
http://docs.unity3d.com/ScriptReference/Rigidbody2D-interpolation.html
Your answer
Follow this Question
Related Questions
Moving an object smoothly over predetermined distance without defining begin and end points 0 Answers
[Solved] Linear movement speed, reset position 1 Answer
Moving walls in multiple places 1 Answer
How can I move a Kinematic Rigidbody2d along the x-axis? 1 Answer
How can I move an object between two positions, while it is on a rotating platform? 0 Answers