So I’ve been trying to make a sort of detection system for a game, and using raycasts to find what is in the trigger zone of an enemy, using a box as a trigger for testing. I decided to use Debug.DrawRay, and the ray just keeps going down. I think it might have something to do with how I’m calculating stuff in my character controller.
Here’s the code for the detection I’ve been working on:
public void Alert(Collider Other) {
Debug.Log("Start");
Ray ray = new Ray(transform.position,Other.transform.position-transform.position);
RaycastHit hit;
if(Other.gameObject.tag.Equals("Player"))
if (Physics.Raycast(ray, out hit, 4))
{
Debug.Log("If1");
Debug.Log(hit.collider.gameObject.tag);
Debug.DrawRay(transform.position,Other.transform.position-transform.position,Color.cyan);
Debug.Log(Other.transform.position);
if (hit.collider.gameObject.tag.Equals("Player"))
{
Debug.Log("If2");
mr.material.SetColor("_Color", Color.yellow);
}
}
}
And here’s the code for the character controller:
public class PlayerControls : MonoBehaviour {
public float mSpeed = 3.0f;
public float mSen = 2.0f;
public float velocity = 0.0f;
public float jSpeed = 15.0f;
private float camRot = 0.0f;
public float camLimit = 60.0f;
public bool doubleJump = true;
public bool ground = true;
CharacterController cc;
// Use this for initialization
void Start ()
{
Cursor.visible = false;
cc = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update ()
{
//rotation
float rotHor = Input.GetAxis("Mouse X")*mSen;
camRot -= Input.GetAxis("Mouse Y")*mSen;
camRot = Mathf.Clamp(camRot, -camLimit, 90.0f);
transform.Rotate(0, rotHor, 0);
Camera.main.transform.localRotation = Quaternion.Euler(camRot, 0, 0);
//Movement
float fSpeed = Input.GetAxis("Vertical")*mSpeed;
float sSpeed = Input.GetAxis("Horizontal")*mSpeed;
if ((cc.collisionFlags == CollisionFlags.Sides && velocity <= 0) && (fSpeed!=0|| sSpeed!=0))
velocity += Physics.gravity.y * Time.deltaTime / 15;
else if (cc.collisionFlags != CollisionFlags.Sides || velocity >= 0)
velocity += Physics.gravity.y* Time.deltaTime;
if (cc.isGrounded)
velocity = -0.5f;
if (Input.GetButtonDown("Jump"))
{
if(cc.isGrounded)
velocity = jSpeed;
else if (doubleJump && cc.collisionFlags == CollisionFlags.Sides)
{
velocity = jSpeed;
doubleJump = false;
}
}
if (!doubleJump && cc.isGrounded)
doubleJump = true;
Vector3 s = new Vector3(sSpeed, velocity, fSpeed);
s = transform.rotation * s;
ground = cc.isGrounded;
cc.Move(s*Time.deltaTime);
}
}
EDIT: Picture for clarity: