I need to rotate a RigidBody
from a script that is pushed by an AddForce(, ForceMode.VelocityChange)
from another script. So far, angularVelocity
is making the RigidBody
rotate, but somehow the AddForce
and angularVelocity
doesn’t mix as I hoped it would. What happens is that the RigidBody
rotates in place and is still following it’s initial trajectory.
My code for AddForce
is;
rb.AddForce(transform.forward * projectileSpd * Time.deltaTime, ForceMode.VelocityChange);
And this is my code that uses angularVelocity
;
void SeekTarget(){
rb = gameObject.GetComponent<Rigidbody>();
Vector3 turnDir = closestTarget.transform.position - rb.position;
turnDir.Normalize();
float rotateAmt = Vector3.Cross(turnDir, transform.forward).y;
rb.angularVelocity = rb.transform.up * -rotateAmt * turnSpd * Time.deltaTime;
}
Both of them are called in FixedUpdate
UPDATE:
I’m adding I bit more detail so you guys can visualize my dilemma. So, here is how I made my projectile.
Projectile prefab
--Projectile handler script
|--rb.AddForce
--Seek handler script
|--rb.angularVelocity
My function for firing the projectile
void FireProjectile(GameObject projectile){
Rigidbody rb = projectile.AddComponent<Rigidbody>();
rb.useGravity = false;
ProjectileHandler projectileHandler = projectile.GetComponent<ProjectileHandler>();
projectileHandler.mSpeed = projectileSpd;
rb.AddRelativeForce(Vector3.forward * projectileSpd * Time.deltaTime, ForceMode.VelocityChange);
projectile.transform.parent = null;
}
So, I think, being that the rb of the both scripts are the same, AddForce
and angularVelocity
should mix. Unfortunately, it doesn’t. Btw, I get the projectile from a pool before I fire it, which I parent to the “gun”.
I remembered something. I don’t have a RigidBody
initially on the prefab itself. Because the projectile GameObject
doesn’t follow it’s “gun” parent if it initially do IIRC. So what I did is, if I’m about to fire the projectile, I’ll do a ‘AddComponent()’ then AddForce
on that rb. But still, seek handler script would get the same rb, right?
This is the video of how my game is currently working. Sorry for it being quite late. The white cylinder is what the projectile should point towards to. my case demo.mp4 - Google Drive