- Home /
The question is answered, right answer was accepted
Transform Screen Point to Transform extension
I have a problem I had a couple of times now and need a universal solution to it.
Basically the question is: How do I get the red vector to touch the blue one, no matter the length?
The picture shows a camera and it's view frustum. The first orthogonal line is the near clipping plane. The red vector Indicates a point on screen transformed into world space on the plane. What I need is the position at the tip of the red vector.
The thick black bar is the plane/ Vector I want to cross with that arrow, in this case it's the forward vector (blue) of the green sphere. I know how to get the pink point just by transforming the screen position to that depth, but I have no idea how to get to the tip of the vector.
I don't want to use a raycast, because it's not just moving a character on a flat floor around but several places I need to do this. Like transforming a touch into the 2D movement plane of a spaceship. It works as long as camera looks perfectly straight at the plane, but at an angle I don't know how to do that.
Trying to use Project didn't help much because no matter how I put it I always the the shorter vector.
Answer by hexagonius · Feb 16, 2017 at 02:12 PM
I pretty much came up with a solution myself:
public Vector3 GetPointOnPlane(Vector3 planeCenter, Vector3 planeNormal, Vector3 origin, Vector3 direction){
var p = new Plane(planeNormal, planeCenter);
float pointToPlaneDistance = p.GetDistanceToPoint (origin);
float partTowardsPlane = Vector3.Dot (direction, -planeNormal);
float scalar = pointToPlaneDistance / partTowardsPlane;
return origin + direction * scalar;
}
Parameters:
planeCenter: some point in space that goes through the imaginative plane
planeNormal: the normalised direction the plane faces
origin: another point in space from where the direction and distance to plane are measured
direction: a direction vector of which the tip should finally end on the plane