Reputation: 23
Tell me how to make a smooth movement of the object. At first, I used: transform.position = new Vector3(transform.position.x + 1.245, transform.position.y, transform.position.z);
but it's just teleportation. I need the object to move 1.245 in 0.3 seconds. How can i do this?
Upvotes: 1
Views: 999
Reputation: 2309
For the best results (which the other answers don't discuss) you will need to move objects using Time.DeltaTime
as a modifier. For your piece of code, this would be:
transform.position = new Vector3(transform.position.x + (1.245 * Time.DeltaTime), transform.position.y, transform.position.z);
This will multiply your "speed value" of 1.245 with the time that passed between frames. This will guarantee smooth movement.
For moving 1.245 units over 0.3 seconds, you will need to move 0.3 / 1.245
units per Update loop for 0.3 seconds.
Upvotes: 0
Reputation: 181
you moving your object with position and its just using for teleporting character
you can use rigidbody or character controller
for example
using UnityEngine;
public class Character : MonoBehaviour
{
Rigidbody rigidbody;
private void Start()
{
// Befor runing the game you must add Rigidbody component to your character gameobject
rigidbody = GetComponent<Rigidbody>();
}
float moveSpeed = 1.245f;
private void Update()
{
float hor = Input.GetAxis("Horizontal") * moveSpeed; // x axis
float ver = Input.GetAxis("Vertical") * moveSpeed; // z axis
float jump = Input.GetAxis("Jump") * moveSpeed; // y axis
// velocity is a local position the character moveing to that
rigidbody.velocity = new Vector3(x: hor, y: jump, z: ver);
}
}
Upvotes: 0
Reputation: 5933
For a smooth transition, you need an interpolation method.
For example linear interpolation:
a * (1.0 - f) + b * f
where a
and b
are vectors and f
is a floating point value between 0.0 and 1.0 (e.g. fraction of passed time).
You could use different interpolation methods too, for example smoothstep, hermite, catmull-rom or bezier cuves.
Unity documentation (with example): Vector3.Lerp
Upvotes: 1