- Home /
Extend a vector3 calculated from the difference between two vectors?
I'm trying to create a third person camera lock on system. If the player decides to lock on to an enemy, I want the camera to automatically center on the enemy and no longer accept input from the player. I got a basic script working to get the point in 3D space for the camera's position based on the direction between the player and enemy but I'm not sure if this is the best way to calculate this.
Here is the code I have so far. I'm afraid I may be missing some basic math that could be doing this simpler without having to resort to using the ".normalized".
var direction = (player.position - enemy.position).normalized;
var cameraDestination = player.position + (direction * offset);
Below is an image of what I'm trying to get (I'm trying to calculate where the blue dot should be in relation to the player and enemy).
If you want a set 'offset' as you have currently, you need the normalize, looks good to me!
Just what i was about to add ^^.
If a fix distance to the player is desired there's no way around normalizing the direction since the (non-normalized) direction depends on the distance between the player and the enemy.
@Scribe, yes I did want a constant offset. Thanks for confir$$anonymous$$g this for me. I'm such a noob. :D
Answer by YoungDeveloper · Sep 05, 2015 at 12:16 PM
Why do think this approach is not simple?
You code does not have any problems, everything should be working fine.
Although I'm not new to program$$anonymous$$g, I am very new to Unity3D and game related math. I was just wanting to make sure I wasn't missing a better way to do this sort of thing as it seems very fundamental.
Answer by wibble82 · Sep 05, 2015 at 12:39 PM
Looks perfectly valid to me. Only simplifcations you could theoretically make would be:
if you want the camera to be the same distance from the player as the player was from the enemy, then you just need to add the 'direction' without normalizing it
if offset is 0 then you obviously don't need to do anything :)
I'm guessing neither of those is true though, so you've got it exactly right. Nothing wrong with a normalize - they're on of the more expensive mathematical operations, but still very cheap compared to all the other stuff that's going on every frame.
Your answer
Follow this Question
Related Questions
what is Vector3.normalized? 1 Answer
Application.LoadLevel problem. 1 Answer
Can you trick a Ui Button that it is being clicked with code? 3 Answers
difference between Gameobject.findobjectoftype<...>(); and simple findobjectoftype<...>(); ? 2 Answers
Axis disabled? (IO have not changed default input except fire1 and fire2) ? 0 Answers