- Home /
needed velocity to reach target in required duration
hi all,
i have a cube and i would like to move it horizantally x meters distance in t duration so what should be cube velocity to reach the target position in t duration? what is the formulate?
Velocity is defined as distance over time. You have your velocity already:
var x = 10f
var t = 3f
var velocity = x / t;
i am applying like this it does not work correctly. hero object does not move target position exactly.
hero.GetComponent ().velocity = -hero.transform.right * ((target.x - hero.transform.position.x) / duration);
If the cube is on the ground (and affected by gravity), the built-in physics calculations take place after your scripts for a given frame, so friction with the ground would slow your object after you define a velocity.
Answer by badadam · Jan 10, 2019 at 07:47 PM
Add this script as a component of cube you want to move. Create an empty gameobject named "targetPoint" whose x value equals to x value of your target place.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveCube : MonoBehaviour {
private Transform targetPoint;
private Rigidbody rb;
public float duration;
private void Awake()
{
rb = GetComponent<Rigidbody>();
targetPoint = GameObject.Find("targetPoint").GetComponent<Transform>();
}
private void Start()
{
float xDistance = targetPoint.position.x - transform.position.x;
float speedX = xDistance / duration;
rb.velocity = new Vector3(speedX,0,0);
}
}
Answer by ysnky · Jan 11, 2019 at 07:51 AM
it is on the ground and we should care of the gravity. but how should i implement when take account of gravity?