- Home /
Instantiating in a position relative to an object.
Hey, I'm trying to make a ship's missile appear 5 units from the ship but from the ship's perspective, not the world coordinates. As is, the missile appears at the ship's world z-coordinate plus 5, so at certain angles the missile collides with the ship.
My code so far:
function Fire(){
if (transform.position.x >= -140 && transform.position.x <= 140 && transform.position.z <= 134 && transform.position.z >= -95) {
audio.Play();
Instantiate(projectile, Vector3(transform.position.x, transform.position.y, transform.position.z + 5), transform.rotation);
gameObject.SendMessage ("Shoot", SendMessageOptions.DontRequireReceiver);
}
state = State.MOVING;
}
Answer by Damyan · Jan 07, 2011 at 01:59 PM
You need to convert your offset from the local coordinate system (ie relative to your ship) to the world's coordinate system. You can do this by applying the transform's rotation to your offset:
var localOffset = Vector3(0,0,5);
var worldOffset = transform.rotation * localOffset;
var spawnPosition = transform.position + worldOffset;
hi man, can you write your code in c#? thank you so much!
Answer by Amyr · Jan 09, 2015 at 12:28 PM
Vector3 localOffset = new Vector3(0,0,5);
Vector3 worldOffset = transform.rotation * localOffset;
Vector3 spawnPosition = transform.position + worldOffset;
But I do this in a different way. I create empty objects and make them child of my ship. I put this empty game objects in the position/orientation I wish the fire to spawn. Since they are children of the ship, they will rotate and translate accordingly, whenever you move the ship. I call those objects (Transforms) cannonPosition1, cannonPosition2, etc.
Then I simply instantiate like this:
Instantiate(projectile, cannonPosition.position, cannonPosition.rotation);
Notice that this way you can also make the cannon shoot in directions that are different from the ships orientation. Its useful if you want to make an intelligent cannon that aims by itself. You only have to properly control the cannonPosition transforms. Remember to make them child of the ship, so they navigate properly with the ship.
The empty object trick worked great for me - you can mount any number of handles onto an object, use them as references - and edit their position and rotation visually in the editor.
Camera.main.transform.position = Handle.transform.position;
Camera.main.transform.rotation = Handle.transform.rotation;
Your answer

Follow this Question
Related Questions
GameObject.Find - Need help... 1 Answer
Enemy Instantiating one bullet 3 Answers
Multiplayer Projectile Instantiation 1 Answer
NavMesh giving jerky like motion 0 Answers
Make object move in a direction depending on where it spawns? (C#) 1 Answer