- Home /
Give object velocity based on spawn object rotation?
I have a spawn cube on the gun in my game. The Z axis of the cube is pointing forward away from the gun. I want to instantiate an object at that point with a random rotation (i have this working properly) but i cant figure out how to give the object forward(Z) velocity based on the spawn object and not based on the object spawned. How do i do this? an example script would be great, to help my understanding. Thanks
Answer by GADoyle · Mar 14, 2013 at 06:29 AM
instead of saying
rigidbody.velocity = Vector3(0,0,20);
you should be able to say
rigidbody.velocity = spawnObject.forward * speed;
the important part is the spawnObject.forward, that will return a normalized vector representing the direction that the spawnObject is facing.
though OperationDogBird is right, velocity is not usually set directly, it sounds like in the context you're using it, i should work.
Answer by OperationDogBird · Mar 13, 2013 at 11:51 PM
You should reference the spawn object when giving the initial velocity rather than using the newly spawned object. Something like
var spawnObject:Transform;
var projectile:Transform;
function SpawnProjectile(){
projectile = Instantiate(....
projectile.rigidbody.AddForce(spawnObject.forward * 20,ForceMode.Force);
}
that didnt work it just glitched up the gun and change the fire rate. and location of the spawn point. it didnt give the spawned object any velocity
rigidbody.velocity = Vector3(0,0,20);
this is what i have now but this is based on the global rotation so no matter where i aim the object goes the same way. I want to change this so that it is based off of the rotation of a specified spawnObject.
I have never altered the velocity property directly as per Unity Docs "In most cases you should not modify the velocity directly, as this can result in unrealistic behaviour." I always use the AddForce method, but i suppose you may have a reason for doing so.
As per my answer, reference whichever transform direction you need of the spawnPointObject. You will need a reference to the spawn point object, an example being: spawnPointObject.transform.forward.
If you are still having issues with this i suggest posting your code so (someone else) or i can write a more specifically accurate answer.
Your answer
Follow this Question
Related Questions
rate of spawn based on speed of object 1 Answer
Problem with Intantiate using uLink! 2 Answers
Self Clone 2 Answers
Spawning if there is space 1 Answer
how do I keep each cloned object at a certain point after trigger 0 Answers