Noticias

¡RECUERDA QUE SI ERES UN NUEVO USUARIO, DEBES PRESENTARTE PARA PODER PUBLICAR MENSAJES! | TENEMOS CANAL OFICIAL DE TELEGRAM: t.me/unity3dspain

Problema con Raycast en 2.5D - Enemigos te persiguen

Iniciado por Bydark, Noviembre 22, 2018, 10:32:12 PM

Tema anterior - Siguiente tema
Estoy haciendo un juego donde el personaje y Npcs son sprites, pero el resto de cosas son elementos 3D.
 
 
 
Lo que quiero es que los enemigos me persigan y para ello he intentado adaptar un script que lo hace pero en 2D, os dejo el script y más abajo un enlace de como se comporta el personaje, a ver si me podéis echar una mano, intuyo que hay que cambiar algunas cosillas para que funcione en los ejes tan particulares que tiene este juego.
 
 
 
EJEMPLO DEL RAYCAST
 
 
 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour {
    // Variables para gestionar el radio de visión, el de ataque y la velocidad
    public float visionRadius;
    public float attackRadius;
    public float speed;
    // Variable para guardar al jugador
    GameObject player;
    // Variable para guardar la posición inicial
    Vector3 initialPosition;
    // Animador y cuerpo cinemático con la rotación en Z congelada
    Animator anim;
    Rigidbody rb3d;
    void Start () {
        // Recuperamos al jugador gracias al Tag
        player = GameObject.FindGameObjectWithTag("Player");
        // Guardamos nuestra posición inicial
        initialPosition = transform.position;
        anim = GetComponent<Animator>();
        rb3d = GetComponent<Rigidbody>();
    }
    void Update () {
        // Por defecto nuestro target siempre será nuestra posición inicial
        Vector3 target = initialPosition;
        // Comprobamos un Raycast del enemigo hasta el jugador
   RaycastHit2D hit =   Physics2D.Raycast(
            transform.position,
            player.transform.position - transform.position,
            visionRadius,
            1 << LayerMask.NameToLayer("Default")
                // Poner el propio Enemy en una layer distinta a Default para evitar el raycast
                // También poner al objeto Attack y al Prefab Slash una Layer Attack
                // Sino los detectará como entorno y se mueve atrás al hacer ataques
        );
        // Aquí podemos debugear el Raycast
        Vector3 forward = transform.TransformDirection(player.transform.position - transform.position);
        Debug.DrawRay(transform.position, forward, Color.red);
        // Si el Raycast encuentra al jugador lo ponemos de target
        if (hit.collider != null) {
            if (hit.collider.tag == "Player"){
                target = player.transform.position;
            }
        }
        // Calculamos la distancia y dirección actual hasta el target
        float distance = Vector3.Distance(target, transform.position);
        Vector3 dir = (target - transform.position).normalized;
        // Si es el enemigo y está en rango de ataque nos paramos y le atacamos
        if (target != initialPosition && distance < attackRadius){
            // Aquí le atacaríamos, pero por ahora simplemente cambiamos la animación
            anim.SetFloat("movX", dir.x);
      anim.SetFloat("movZ", dir.z);
            anim.Play("Enemy_Walk", -1, 0);  // Congela la animación de andar
        }
        // En caso contrario nos movemos hacia él
        else {
            rb3d.MovePosition(transform.position + dir * speed * Time.deltaTime);
            // Al movernos establecemos la animación de movimiento
            anim.speed = 1;
            anim.SetFloat("movX", dir.x);
            anim.SetFloat("movZ", dir.z);
            anim.SetBool("walking", true);
        }
        // Una última comprobación para evitar bugs forzando la posición inicial
        if (target == initialPosition && distance < 0.02f){
            transform.position = initialPosition;
            // Y cambiamos la animación de nuevo a Idle
            anim.SetBool("walking", false);
        }
        // Y un debug optativo con una línea hasta el target
        Debug.DrawLine(transform.position, target, Color.green);
    }
    // Podemos dibujar el radio de visión y ataque sobre la escena dibujando una esfera
    void OnDrawGizmosSelected() {
        Gizmos.color = Color.yellow;
        Gizmos.DrawWireSphere(transform.position, visionRadius);
        Gizmos.DrawWireSphere(transform.position, attackRadius);
    }
}

 
 

¿Y lo quieres en un mundo 3D? Pues para empezar usa el RayCast normal, no el RayCast2D.... Algo que te devuelva un rayo en 3D, con la distancia entre los 2 elementos, para que puedas hacer que vaya en la dirección, siguiendo al personaje, etc..

Gracias, ya lo he solucionado, dejo un ejemplo de como se comporta.
 
 
 
EJEMPLO RAYCAST

Etiquetas: