- Home /
Multiple raycast not working?
I have a problem. In my script i use more than 1 raycast, but it seems only the one on top works. If my code is messy please just say so. It's about a 2d game.
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement;
public class Walking : MonoBehaviour {
public bool CanWalkRight = true;
public bool CanWalkLeft = true;
public bool CanWalkUp = true;
public bool CanWalkDown = true;
public int RayDistance;
public KeyCode Right;
public KeyCode Left;
public KeyCode Up;
public KeyCode Down;
public KeyCode restart;
public Rigidbody2D rb;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(restart))
{
Invoke("Restart", 0.5f);
}
Debug.DrawRay(transform.position, Vector2.right, Color.red);
if (Input.GetKeyDown(Right) && CanWalkRight == true)
{
rb.MovePosition(new Vector2(rb.position.x + 1, rb.position.y));
rb.MoveRotation(0);
Invoke("WalkReset", 0.01f);
}
if (Input.GetKeyDown(Left) && CanWalkLeft == true)
{
rb.MovePosition(new Vector2(rb.position.x + -1, rb.position.y));
rb.MoveRotation(180);
Invoke("WalkReset", 0.01f);
}
if (Input.GetKeyDown(Up) && CanWalkUp == true)
{
rb.MovePosition(new Vector2(rb.position.x, rb.position.y + 1));
rb.MoveRotation(90);
Invoke("WalkReset", 0.01f);
}
if (Input.GetKeyDown(Down) && CanWalkDown == true)
{
rb.MovePosition(new Vector2(rb.position.x, rb.position.y + -1));
rb.MoveRotation(270);
Invoke("WalkReset", 0.01f);
}
RaycastHit2D HitRight = Physics2D.Raycast(transform.position, Vector2.right, RayDistance);
if (HitRight.collider.tag.Equals("Object"))
{
CanWalkRight = false;
}
Debug.Log("d");
RaycastHit2D HitLeft = Physics2D.Raycast(transform.position, Vector2.left, RayDistance);
if (HitLeft.collider.tag.Equals("Object"))
{
CanWalkLeft = false;
}
RaycastHit2D HitUp = Physics2D.Raycast(transform.position, Vector2.up, RayDistance);
if (HitUp.collider.tag.Equals("Object"))
{
CanWalkUp = false;
}
RaycastHit2D HitDown = Physics2D.Raycast(transform.position, Vector2.down, RayDistance);
if (HitDown.collider.tag.Equals("Object"))
{
CanWalkDown = false;
}
Debug.DrawRay(transform.position, Vector2.right, Color.red);
}
private void WalkReset()
{
CanWalkRight = true;
CanWalkLeft = true;
CanWalkUp = true;
CanWalkDown = true;
}
private void Restart()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
Comment
If you are looking for whether sth is blocking your way or not, why don't you just use colliders? It's easier to manage
Your answer
Follow this Question
Related Questions
Getting a Raycast rope to follow its object 0 Answers
Physics2D.Raycasting questions 0 Answers
Multiple Cars not working 1 Answer
Button blocking raycast 3 Answers
Raycast for a 2D objects 0 Answers