- Home /
localposition not working? Calculating a vector in front of an object. Picture and code included
I am making a 3D spaceship combat minigame.
I need to launch a projectile from my spaceship, towards a position that is the targeted enemy position, adding 30 or something to the local Z of that position (i.e, "shooting it ahead of the enemys forward path), but I need to be grabbing that vector when the shot is instantiated, so that it is traveling in a straight line (interpolating / following / lookat is not what i need).
Here is what I have, and it is working as coded, but the calculation that adds to the Z position ends up giving me a vector that is higher than the Z axis value in the world space, despite me using localposition. what I need is, that vector to end up as higher than the ships Z axis value, so it is "In front of where the ship / target" was at the moment of that calculation.
void Start () {
player = GameObject.FindWithTag ("Player").GetComponent <Player> ();
Destroyshot ();
hasTarget = player.seesTarget;
if (hasTarget) {
target = player.locktarget;
targetahead = new Vector3 (target.localPosition.x, target.localPosition.y, target.localPosition.z + 30);
transform.LookAt (targetahead);
}
}
void Update () {
gameObject.transform.Translate (Vector3.forward * speed);
Debug.DrawLine (gameObject.transform.position, targetahead);
}
Answer by hexagonius · Jan 12, 2017 at 06:43 AM
the problem is that your LookAt is looking at a position that is still in localspace of the target. it's actually even easier to calculate what you want in world space directly:
target.position + target.forward * 30;
Wow, thanks! +Rep! Now ins$$anonymous$$d of 30, I can decide that amount based on the velocity of the target's rigidbody!
While I have you, any idea on how I could go about that with some accuracy?
I have "2 * enemyvelocity" and it is pretty accurate, but doesn't take into account the distance betwen the player and enemy when fired.
I was thinking...Pythagorean theorem?
Your answer
Follow this Question
Related Questions
Class member Vector3 based on local transform 1 Answer
Finding the forward vector of a child in local space? 3 Answers
How can I get an OverlapBox with the exact same size and position as a BoxCollider? 1 Answer
Locking gameobject to rotating floor 0 Answers
move a transform to a vector 3? 2 Answers