- Home /
interesting raycast question
Hello people,
I have a (what I believe) interesting question about raycasts.
The behaviour I want:
I'm working on a project where you have the ability to teleport to a certain point in front of you (let's say 6 meters in front of you). Now what I want to avoid is that you teleport in another collider (or outside the map, but that one isn't that difficult).
if there is a better method to get this, please do enlighten me!
What I plan on trying:
I wanted to know if there is a way to call a point in your raycast. So not the hit point but somewhere between the hitpoint AND the one that casts.
so there are 2 things I want to know.
1: is this possible? 2: do you know a better way to do it?
sincerely, me
Answer by robertbu · Feb 20, 2014 at 04:38 PM
In order to solve this problem, you need to figure out some way to handle the fact that your character has some size. That is, say your Raycast failed at exactly 6 units, and you cast the ray from your character position, if you moved your character to that position, the character would be 1/2 inside the object that was hit.
So I'm going to define 'charRadius' as the distance from the pivot point of your character and the front of your character, and 'desiredDist' as the distance you would like to travel if you do not hit anything, and assume you want to move in the current forward direction of your character:
var charRadius = 0.75;
var desiredDist = 6.0;
function TeleportForward () {
var hit : RaycastHit;
if (Physics.Raycast(transform.position, transform.forward, hit, desiredDist+charRadius)) {
var dir = (transform.position - hit.point).normalized;
transform.position = hit.point + dir * charRadius;
}
else {
transform.position += transform.forward * desiredDist;
}
}
The part of this code that directly answer your questions is these two lines:
var dir = (transform.position - hit.point).normalized;
transform.position = hit.point + dir * charRadius;
It calculates a vector from the hit point back towards the character. Then it set the position 'charRadius' along that vector. The result is that the front of your character should just be touching the surface the ray cast hit.
Answer by thornekey · Feb 20, 2014 at 04:08 PM
u could get the distance of the ray and divide by 2 and then add that amount to ur location? lol i dont even know if that will work.. its 3 am
Your answer
Follow this Question
Related Questions
Find a point at a distance from point on a line passing through two points 1 Answer
How do you use a queuing mechanism in Unity? 1 Answer
Can Raycast get multiple points from the same collider? 1 Answer
Raycasting to get an exact point on an object. 2 Answers
Trying to cast a ray towards an imaginary wall and get a "hit" / "end" point 2 Answers