Raycast inconsistent
Hi, I have a teleportation script that will teleport a player to where the mouse is or to first wall hit, like this:
private void Leap()
{
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(player.transform.position, mousePos, Mathf.Infinity, mask);
if (hit.collider != null)
{
player.transform.position = new Vector3(hit.transform.position.x, hit.transform.position.y, 0);
}
else
{
player.transform.position = new Vector3(mousePos.x, mousePos.y, 0);
}
}
If I stand too far from the wall that should stop the Raycast, it fails to hit more often then if I stand far away from it. That means I easily can teleport past that wall if I am standing far enough from it.
The red walls should stop me from teleporting past them: https://dl.dropboxusercontent.com/s/41bk74r7q1kjpxb/raycast_bug.gif
The problem is that the if/else case gets executed before the Raycast has finished...
Until proven otherwise i'd say that's impossible.
Why is this only working sometimes? I put a gif to show you how it works.
Answer by Morgenstern_1 · Oct 14, 2016 at 03:47 PM
Raycast is synchronous, so that's not the problem.
I'm not sure your move code will work as you expect though - it'll only work when you're going from a certain direction. You'll always spawn 0.3 units before whatever wall you're aiming at, 0.3 units below it and at 0 on the z access.
Yes, this part is wrong, but it is not the cause of my problem.
Your answer
Follow this Question
Related Questions
Issue with Raycast hit.distance Variables Reseting Itself 0 Answers
Bullets with raycast and physics 2 Answers
Need help with Ray casting syntax. 1 Answer
Making a portal inspired game - Need help! 0 Answers
Plane is blocked all Raycast 0 Answers