- Home /
Question by
MoOuhami7 · Nov 12, 2020 at 05:21 PM ·
2d-platformerdetectionraycasthit2d
How to set a condition for not colliding with an object using RayCast2D ?
Hello Unity community ! I want set an enemy to stop whenever my player gets closer to him ! That condition was established. The problem now is that I want It to get back walking if the player moved away from It. I tried reversing the conditions and using the else statement, but no results Here is the snippet of code I am currently using :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyMovement : MonoBehaviour
{
// Variables
float speed;
public Transform Detection;
bool IsmovingRight = true;
float normalSpeed = 3f;
private void Update()
{
RaycastHit2D groundInfo = Physics2D.Raycast(Detection.position, Vector2.down, .1f);
RaycastHit2D playerInfoRight = Physics2D.Raycast(Detection.position, Vector2.right, 3f);
RaycastHit2D playerInfoLeft = Physics2D.Raycast(Detection.position, Vector2.left, 4f);
// Setting an embarked if statements, to see If the raycast has hit anything
if (playerInfoLeft.collider.CompareTag("Player") || playerInfoRight.collider.CompareTag("Player"))
{
speed = 0;
Debug.Log("Got you !");
}
else
{
speed = 3f;
Debug.Log("Where is he ?");
}
}
}
Comment