Question by
ollie_payne · Jun 05, 2016 at 04:11 PM ·
raycastraycasthit2d
Raycast2D not detecting a certain object
I have made a basic enemy ai script for my 2D game. I have the enemy raycasting in the direction he is facing, to detect for the player. However, the enemy detects all other objects but never seems to detect the player. I am completely stumped so any and all help is appreciated. Thank you.
using UnityEngine;
using System.Collections;
public class SkeletonSoul : MonoBehaviour {
RaycastHit2D hit;
Vector2 rayDirection;
bool movingLeft = false;
bool movingRight = true;
public Transform destinationLeft;
public Transform destinationRight;
public float patrolSpeed;
public float attackChargeSpeed;
void Update () {
hit = Physics2D.Raycast (transform.position, rayDirection, 1f);
Debug.DrawRay (transform.position, rayDirection, Color.red);
if (hit.collider.name != null) {
Debug.Log (hit.collider.name);
}
//The skeleton soul is moving to the right
if (movingRight == true) {
rayDirection = Vector2.right;
transform.localScale = new Vector3 (1, 1, 1); //Make the skeleton soul face to the right when moving right
transform.position += Vector3.right * patrolSpeed * Time.deltaTime;
if (transform.position.x > destinationRight.position.x) {
movingLeft = true;
movingRight = false;
}
}
//The skeleton soul is moving to the left
if (movingLeft == true) {
rayDirection = Vector2.left;
transform.localScale = new Vector3 (-1, 1, 1); //Make the skeleton soul face to the left when moving left
transform.position += Vector3.left * patrolSpeed * Time.deltaTime;
if (transform.position.x < destinationLeft.position.x) {
movingRight = true;
movingLeft = false;
}
}
}
}
Comment
@Hellium The player has a Box Collider 2D attached to it.
Answer by kristof1104 · Jun 05, 2016 at 08:23 PM
Got this from the wiki:
"If you move Colliders from scripting or by animation, you need to allow at least one FixedUpdate to be executed so that the physics library can update before a Raycast will hit the Collider at its new position".
http://docs.unity3d.com/ScriptReference/Physics.Raycast.html
Your answer
![](https://koobas.hobune.stream/wayback/20220612082237im_/https://answers.unity.com/themes/thub/images/avi.jpg)