Untitled
unknown
csharp
10 months ago
3.2 kB
7
Indexable
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ghostMove : MonoBehaviour
{
public float speed = 0.5F; // Velocidad del fantasma
private Vector2 direction; // Dirección actual del movimiento
private Rigidbody2D rb; // Referencia al Rigidbody2D
public float rayDistance = 0.2f; // Distancia para detectar obstáculos
public LayerMask obstacleLayer; // Capa de los obstáculos (paredes)
void Start()
{
rb = GetComponent<Rigidbody2D>(); // Obtener el Rigidbody2D
ChooseRandomDirection(); // Escoge una dirección inicial
}
void Update()
{
// Actualiza la velocidad en la dirección actual
rb.velocity = direction * speed;
// Comprueba si está cerca de un obstáculo
if (IsNearObstacle(direction))
{
ChooseRandomDirection();
}
}
void ChooseRandomDirection()
{
// Guarda la dirección actual
Vector2 previousDirection = direction;
// Array de posibles direcciones
Vector2[] possibleDirections = { Vector2.up, Vector2.down, Vector2.left, Vector2.right };
Vector2 newDirection = Vector2.zero;
// Lista de direcciones válidas
List<Vector2> validDirections = new List<Vector2>();
// Comprueba cuáles direcciones son válidas
foreach (var dir in possibleDirections)
{
if (IsDirectionValid(dir))
{
validDirections.Add(dir);
}
}
// Si hay direcciones válidas, elige una aleatoria que no sea la anterior
if (validDirections.Count > 0)
{
do
{
int random = Random.Range(0, validDirections.Count);
newDirection = validDirections[random];
} while (newDirection == previousDirection && validDirections.Count > 1);
}
// Asigna la nueva dirección
direction = newDirection;
}
// Método para verificar si una dirección es válida
private bool IsDirectionValid(Vector2 dir)
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, dir, 0.5f, obstacleLayer);
// Debug del rayo (verde si no hay colisión, rojo si hay colisión)
Color rayColor = hit.collider == null ? Color.yellow : Color.yellow;
Debug.DrawRay(transform.position, dir * 0.5f, rayColor, 0.5f);
return hit.collider == null; // Si no hay colisión, la dirección es válida
}
// Método para verificar si hay un obstáculo cercano
private bool IsNearObstacle(Vector2 dir)
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, dir, rayDistance, obstacleLayer);
// Debug del rayo para obstáculos cercanos
Color rayColor = hit.collider != null && hit.distance <= rayDistance ? Color.yellow : Color.blue;
Debug.DrawRay(transform.position, dir * rayDistance, rayColor, 0.1f);
// Si hay una colisión y está dentro del rango, retorna true
return hit.collider != null && hit.distance <= rayDistance;
}
}
Editor is loading...
Leave a Comment