Find point at distance along a vector - unity3d

Given a known direction and range I'm trying to calculate the 3D position along the vector at that range from the starting point.
To do this I'm basically following the Unity manual and the solution offered in various other questions about this topic:
Take your direction, normalise it and multiply by the required
distance.
This isn't working for me but I can't figure out what's wrong. Here's my code that should draw a line from the starting point towards the mouse cursor position, ending at the given distance from the starting point:
IEnumerator DrawLineToMouse(float range)
{
RayCastHit hit;
Vector3 endPos;
float rangeSquared = Mathf.Sqrt(range);
while (Input.GetButton("Fire1"))
{
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 2000))
{
endPos = (hit.point - startPos).normalized * rangeSquared; // startPos is the starting point of the line to be drawn
Debug.DrawLine(startPos, hit.point, Color.green, Time.deltaTime);
Debug.DrawLine(startPos, endPos, Color.red, Time.deltaTime);
}
yield return null;
}
}
For some reason the direction seems off. In this picture the green Debug.Draw line is direct from the starting point to the mouse position, the red line is to the calculated vector:
I've tried both perspective and orthographic cameras, and I've tried varying the starting point, the problem is the same. I don't know what to try regarding the code because everything I've read suggests it should work.
What could be the problem?

Currently your endPos is at the vector distance and direction but starting from 0,0,0
Instead it should rather be
endPos = startPos + (hit.point - startPos).normalized * rangeSquared;
or for better understanding
var distance = rangeSquared;
var direction = (hit.point - startPos).normalized;
endPos = startPos + direction * distance;

Related

Drawing a line in the direction a player is moving

For debugging purposes I am trying to draw 2 debug lines. One in the direction that the character is facing and one in the direction that the character is moving.
I have the following function that is called in the update method.
void DrawDirectionLines()
{
var wishDir = transform.position + transform.forward;
var movementDir = Quaternion.LookRotation(rb.velocity).eulerAngles;
Debug.DrawLine(transform.position, transform.position + transform.forward * 5, Color.red);
Debug.DrawLine(transform.position, transform.position + movementDir * 5, Color.blue);
}
The red direction debug line works perfectly however the blue line representing the actual movement direction of the player seems to always misbehave and never points in the direction the player is moving in.
Does anybody know how I can fix this?
The problem is because your movemendDir is a Vector3 with the euler angles, and not a direction vector.
The good news is that rb.velocity is the direction you only need. The documentation says: Unity velocity also has the speed in X, Y, and Z defining the direction.
But if you use that velocity vector the lenght of the line will depends on the velocity. The solution is normalize that vector.
You need to replace:
var movementDir = Quaternion.LookRotation(rb.velocity).eulerAngles;
to:
var movementDir = rb.velocity.normalized;

Dragging an object using perspective camera

I'm trying to write a function so when I hold the mouse down I can drag the game object and then I latch it into target.
I'm using a perspective,vertical camera with physical Camera checked and with focal length 35. Also I don't know if this is important but I am dragging the object in the Y and Z axis.
The code I'm using drags the objects too close to the camera. How can I fix this?
private void OnMouseDrag()
{
if (IsLatched)
{
print($"is latched:{IsLatched}");
return;
}
float distance = -Camera.main.transform.position.z + this.transform.position.z;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Vector3 rayPoint = ray.GetPoint(distance);
this.transform.position = rayPoint;
print($"{name} transform.position:{transform.position}");
this.gameObject.GetComponent<Rigidbody>().isKinematic = true;
isHeld = true;
}
You are calculating the distance by subtracting the z coordinates, then taking a point along the click-ray with that distance. That will not be a point on the same z coordinate. If you want to keep one component constant, I would rather intersect the ray with an XY plane.
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float Zplane = this.transform.position.z; // example. use any Z from anywhere here.
// find distance along ray.
float distance = (Zplane-ray.origin.z)/ray.direction.z ;
// that is our point
Vector3 point = ray.origin + ray.direction*distance;
// Z will be equal to Zplane, unless considering rounding errors.
// but can remove that error anyway.
point.z = Zplane;
this.transform.position = point;
Could this help? Would work similar with any other plane.

How to calculate the intersection point of Ray and Vector3 Line

This question is about the Unity C# project.
I know the ray from the camera and the normal vector at the hit point.
Ray from the camera utilizes Camera.main.ScreenPointToRay();
I want to get the intersection of the y-axis values with different ray and normal vectors.
The code and results are as follows.
Ray ray3 = Camera.main.ScreenPointToRay(new Vector3(540, 0));
Debug.DrawRay(ray3.origin, ray3.direction * 10f, Color.yellow, 5f);
Ray ray4 = Camera.main.ScreenPointToRay(new Vector3(540, 499));
Debug.DrawRay(ray4.origin, ray4.direction * 10f, Color.yellow, 5f);
if (Physics.Raycast(ray3, out hit, Mathf.Infinity))
{
var normal = hit.normal;
Vector3 cyanLine = hit.point + normal * 100f;
}
ray3 is the below yellow line.
ray4 is the above yellow line.
the cyan line is normal vector.
The x-axis values are the same, only the y-axis values are different, so the two lines are intersecting each other.
I'd like to know the coordinates of the intersection of Cyan Line and the above yellow ray.
How can I get this value. Thank you in advance.

How to determine thickness vs width? (Using Raycasting)

Visual aids
Thickness vs width: here
Please view the short gif.
Thickness here is different from width as there are multiple walls as there are outer and inner cylinders. Thickness is the measurement of the distance between the outer/inner wall of any side of the cylinder where as thickness is the distance from one end to the other encompassing the hollow space between.
Quick synopsis on the gifs provided
-On every click the origin point (blue) and destination point (orange) orbs are created to denote where the user clicks and the interpreted end point used to calculate the distance (displayed on the GUI).
The origin defines where the user clicks on the surface of an objects collider and the destination defines the point, perpendicular with the world Y axis of the origin, where a second ray cast towards the first ray, hits the other side of the collider.
Current:
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
//obtain the vector where the ray hit the collider.
hitPoint = hit.point; //origin point
//offset the ray, keeping it along the XZ plane of the hit
Vector3 offsetDirection = -1 * hit.normal;
//offset a long way, minimum thickness of the object
ray.origin = hit.point + offsetDirection * 100;
//point the ray back at the first hit point
ray.direction = (hit.point - ray.origin).normalized;
//raycast all, because there might be other objects in the way
RaycastHit[] hits = Physics.RaycastAll(ray);
foreach (RaycastHit h in hits)
{
if (h.collider == hit.collider)
{
hitBack = h.point; //destination point
}
}
}
Currently, width is the functionality in place. I want to calculate thickness without having to go inside of an object (as seen in the gif).
Amazing reference
http://answers.unity3d.com/questions/386698/detecting-how-many-times-a-raycast-collides-with-a.html
This guy basically had the same question as me and has a solution that could possibly work. I'm not sure how Linecasting works vs Raycasting.
Keep:
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
//obtain the vector where the ray hit the collider.
hitPoint = hit.point; //origin point
//offset the ray, keeping it along the XZ plane of the hit
Vector3 offsetDirection = -1 * hit.normal;
//offset a long way, minimum thickness of the object
ray.origin = hit.point + offsetDirection * 100;
//point the ray back at the first hit point
ray.direction = (hit.point - ray.origin).normalized;
Replace:
//raycast all, because there might be other objects in the way
RaycastHit[] hits = Physics.RaycastAll(ray);
foreach (RaycastHit h in hits)
{
if (h.collider == hit.collider)
{
hitBack = h.point; //destination point
}
}
With (credits to MirrorMirror's insightful post, and #ryemoss for his instrumental advice and assistance):
int counter = 0;
bool calculating = false; //set this to true on click
Vector3 Point, PreviousPoint, Goal, Direction;
Point = ray.origin;
Goal = hit.point;
Direction = ray.direction;
PreviousPoint = Vector3.zero;
while (calculating == true)
{
counter++;
RaycastHit hit2;
if (Physics.Linecast(Point, Goal, out hit2))
{
if(counter > 100)
{
hitBack = hitPoint;
counter = 0;
calculating = false;
break;
}
PreviousPoint = hit2.point;
Point = hit2.point + (Direction / 10000f);
}
else
{
if (PreviousPoint == Vector3.zero)
hitBack = hitPoint;
else
hitBack = PreviousPoint;
calculating = false;
counter = 0;
}
}
Linecast vs Raycast
With a raycast you set the start point, the direction, and the distance to check in that direction, with a linecast you simply set start and end points and it checks between those 2 points.
So, if you know the end destination specifically, use linecast, if you want to check in a specific direction but have no specific end point, use raycast.
Solution
First, use the initial raycast to obtain the first point, hit.point. Then, set the ray.origin to a point in world space outside the collider (the collider of the object we first collided with to obtain hit.point), and set the ray.direction to face the ray back at the first point, hit.point.
Finally, use a while loop to create a new linecast, at ray.origins new position (updated each time through the while loop until a linecast reaches hit.point), each time a collision with the object occurs until a linecast reaches hit.point. Once hit.point has been reached, it means every surface of the object was hit and on each hit, a new line was created until a line reached the first initial point, hit.point. To calculate thickness, take the distance between the first hit, hit.point, and the hit previous to the reverse linecast hitting hit.point, PreviousPoint.
UPDATE
1-Revise the code to properly handle 1-sided objects (ex: Planes).
2-Added counter to prevent special cases in which calculation not possible.
3-Improve readability.

How to Calculate Target Destination

I'm having a bit of trouble figuring this one out. What I'm trying to achieve is a sort of tackling motion. The player lunges at the target from a distance.
The diagram shows the set up. The blue diamond is the player and the red thing is the target. The purple box is the renderer bounds of the targets SkinnedMeshRenderer. I'm using renderer bounds because some target's mesh are much larger than other. Currently, the player is shooting to the orange star...which is unrealistic. I want him to, no matter what way the target is facing, always target the closest point of the target relative to his position...in the diagram's case that would be the brown star. Here's the code I've been using...
public IEnumerator Blitz()
{
rigidbody.velocity = Vector3.zero; //ZERO OUT THE RIGIDBODY VELOCITY TO GET READY FOR THE BLITZ
SkinnedMeshRenderer image = target.GetComponentInChildren<SkinnedMeshRenderer>();
Vector3 position = image.renderer.bounds.center + image.renderer.bounds.extents;
position.y = target.transform.position.y;
while(Vector3.Distance(transform.position, position) > 0.5f)
{
transform.position = Vector3.Lerp(transform.position, position, Time.deltaTime * 10);
yield return null;
}
Results(); //IRRELEVANT TO THIS PROBLEM. THIS CALCULATES DAMAGE.
Blitz.Stop(); //THE PARTICLE EFFECT ASSOCIATED WITH THE BLITZ.
GetComponent<Animator>().SetBool(moveName, false); //TRANSITIONS OUT OF THE BLITZ ANIMATION
GetComponent<Input>().NotAttacking(); //LET'S THE INPUT SCRIPT KNOW THE PLAYER CAN HAVE CONTROL BACK.
}
//Get the derection to tarvel in and normalize it to length of 1
Vector3 Direction = (Target - transform.position).normalized
With Direction, you can do many things. For example, you can multiply the direction by your speed and add that to your position.
transform.position += Direction * MoveSpeed;
If you want to get to the closest point, you can use the handy Collider.ClosestPointOnBounds method.
Target = TargetObject.GetComponent<Collider>().ClosestPointOnBounds(transform.position)
and plug the Target into the code used to get the direction.
Alternatively, you can use Vector3.Lerp without getting a direction since it's just interpolating.
transform.position = Vector3.Lerp(Target,transform.position,time.DeltaTime);
For stopping at the target point, you can use the arrival behavior.
//Declare the distance to start slowing down
float ClosingDistance = Speed * 2;
//Get the distance to the target
float Distance = (Target - transform.position).magnitude;
//Check if the player needs to slow down
if (Distance < ClosingDistance)
{
//If you're closer than the ClosingDistance, move slower
transform.position += Direction * (MoveSpeed * Distance / ClosingDistance);
}
else{
//If not, move at normal speed
transform.position += Directino * MoveSpeed;
}