- Home /
Direction and Distance from One Object to Another
In the Unity manual it lists a method for getting the direction between two points
// Gets a vector that points from the player's position to the target's.
var heading = target.position - player.position;
var distance = heading.magnitude;
var direction = heading / distance; // This is now the normalized direction.
It looks like the example was done in javascript but I am using C# so I took that calculation and tried to apply it to my work:
// calculate slant angle
Vector3 originVector = new Vector3 (x1,y1,z);
Vector3 outerVector = new Vector3 (x2,y2,z);
Vector3 heading = originVector - outerVector;
float distance = heading.magnitude;
return heading/distance;
The problem I'm having is since magnitude is a float value and everything else is a Vector3 the types are not compatible. The example keeps the types generic but that doesn't seem right as they are specifically talking about making calculations with Vectors.
So my question is how to I get this to work in C# as intended in the linked manual page. Am I just supposed to cast?
This works fine for me, Vector3 has an operator for dividing by floats. Specifically what error messages are you getting, and what line does Unity say they are on?
Answer by kritoa · Jun 08, 2017 at 06:32 AM
What is your function supposed to return?
Vector3 / float is defined: it returns a Vector3 (it divides each component, x,y,z, by the second argument). So this should work just fine. What error are you getting?
Your answer
Follow this Question
Related Questions
Cannot modify a value type return value of `UnityEngine.Transform.position'. Can anyone help ? 1 Answer
Using a variable as a components for Vector3 1 Answer
Getting an array of floats from a .bytes asset 0 Answers
How to cut numbers after decimal point in coordinates? 1 Answer
I want to move a rigid object with following command 1 Answer