How can I get the distance between two points, but on just one axis?

Ultimately I am trying to get the distance of the mouse from an object, but in a single axis, the y or x axis.

So I cant use Vector3.distance.

I thought about simply getting the mouse position in world points: Camera.main.ScreentoWorldPoint(Input.MousePosition) and then getting the y axis from that, and then simply subtracting from my other gameObject - but with the negative numbers I dont think that would work.

Then I looked into Mathf.Abs and I dont think that will help me either, but not sure.

Any thoughts on how I could do this? Thanks.

Why Mathf.Abs is not helping? Since straight-line distance = difference in point on straight line Then distance = Mathf.Abs( x1 - x2 ) or distance = Mathf.Abs( y1 - y2 )

Hmm what if the position.y is negative lets say negative 3, then mathf.abs changes that to positive 3 - will the math still be right? If my position of my object.y is 12, and my position of my mouse.y is -3 - is their distance from eachother on the y access still 9?

3 Answers

3

Vector3.distance just uses a modified Pathagorean Theorem to get this equation. If you break that down to just one axis, that’s:

/* make sure both points are in the same coordinate system. 
 * That is, if you are using the mouse point, either
 * convert it to world coordinates or convert your object
 * to screen coordinates */
Vector difference = pointA - pointB;

var distanceInX = Mathf.Abs(difference.x);
var distanceInY = Mathf.Abs(difference.y);
var distanceInZ = Mathf.Abs(difference.z);

Thanks - this ended up working like I needed. Thank you!

Edit: If you are worried about actual direction, keep this in mind always: vector substraction of A and B gives you a vector that essentially points from one vector to another. that relationship goes like this: direction = to - from

I think you can just do a Vector3.distance check, but having the axis of the target you dont want to check be same as the source like so:

var from:Vector3 = new Vector3(0,0,0);
var to:Vector3 = new Vector3(100,350,999);

Vector3.Distance(from, Vector3(to.x,from.y,from.z));

(for x only in the example)

Thanks very much for coming to answer!

You are welcome :-)

var firstPoint;
var secondPoint;

function Update(){
	if(Input.GetMouseButtonDown(0)){
		var hit: RaycastHit;
		var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
		if(Physics.Raycast(ray, hit)){
			if(firstPoint==null){
				Debug.Log('First Hit point: ' + hit.point);
				firstPoint = hit.point;
			}else{
				Debug.Log('First Hit point: ' + firstPoint + ' + Second Hit point: ' + hit.point);
				secondPoint = hit.point;
				var dist = Vector3.Distance(firstPoint,secondPoint);
				Debug.Log('Distance: ' + dist);
			}
		}
	}
}

it works fine.thanks ....

Thanks. It works great for calculating distance