Reputation: 307
I'm trying to make a type of projectile with Rigidbody:
private void FiredAsProjectile(GameObject target)
{
Vector3 moveVector = Vector3.Zero;
float velMod = 8f // A placeholder value to later calculate with mass / velocity
if(target != null)
{
moveVector = (target.transform.position - transform.position);
m_rb.MovePosition(transform.position + moveVector * Time.deltaTime * velMod);
}
}
This is updated via FixedUpdate upon calling this method somewhere else. I have a few things I needed this to behave: to have velocity output and move to a position, not direction.
However, I'm getting a weird outcome. Even though this object moves as a kinematic rigidbody and its interpolation is set to None this object slows down before reaching the target vector as if it has interpolation. Let's say I wanted a bullet to be fired from the barrel and fly to a point in world instead of direction, that's what I wanted this object to behave like, but not quite so.
Am I missing something or misunderstanding something? Is there a better way to move this kinematic rigidbody whilst still outputting rigidbody.velocity and still collide?
Upvotes: 0
Views: 4787
Reputation: 4249
This happens because you don't Normalize
the moveVector
.
To explain why this happens, we'll suppose that Time.deltaTime = 0.01
every step:
t0
time, let's say that the distance between the moving object (in x = 0) and the target object (x = 100) is 100.MovePosition
is 0 + 100*8*.01 = 8
and the object is moved accordingly to this new position (since you said it's Kinematic without interpolation)t1
time, moveVector = 100-8 = 92
8 + 92*8*.01 = 15.36
Notice that between t0
and t1
you moved 8 units, whereas between t1
and t2
you moved only 7.36 units. So, the more your moving object is near the target object, the less you'll move the object, giving the effect of "slowing down" (and moreover it'll never reach the target object, you'll stop at a distance equal to the minimum floating number precision).
In order to fix this, you just need to normalize the moveVector
, i.e. making its module fixed every step. So, just add this line:
moveVector = (target.transform.position - transform.position);
moveVector.Normalize();
m_rb.MovePosition(transform.position + moveVector * Time.deltaTime * velMod);
and the distance moved every step will always be the same regardless of distance.
Upvotes: 2