Tutorial del controlador de gusanos 3D para Unity

En este tutorial, mostraré cómo crear un controlador de gusano simple en Unity, inspirado en el tutorial de desarrollo de juegos para principiantes TornadoTwins serie.

El controlador del gusano se deslizará con un suave efecto de seguimiento de cola y tendrá la capacidad de saltar.

Los scripts de este tutorial se escribieron originalmente en JavaScript (también conocido como UnityScript), que ya no es compatible, por lo que proporcionaré una alternativa a C#.

Sharp Coder Reproductor de video

Para crear un controlador de gusano en Unity necesitaremos:

  • Crea los guiones necesarios
  • Crea un personaje de gusano
  • Asignar los guiones al personaje.

Paso 1: crea todos los scripts necesarios

Comencemos creando todos los scripts que serán necesarios para configurar un controlador de gusano:

  • Crea un nuevo script, llámalo "SC_WormController" y pega el siguiente código dentro de él:

SC_WormController.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(CharacterController))]
public class SC_WormController : MonoBehaviour
{
    public float speed = 3.0f;
    public float rotateSpeed = 1.0f;
    public float jumpSpeed = 5.0f;
    public float gravity = 9.8f;

    CharacterController controller;
    Vector3 moveDirection;

    // Start is called before the first frame update
    void Start()
    {
        controller = GetComponent<CharacterController>();
    }

    // Update is called once per frame
    void Update()
    {
        // Rotate around y - axis
        transform.Rotate(0, Input.GetAxis("Horizontal") * rotateSpeed, 0);

        // Move forward / backward
        Vector3 forward = transform.TransformDirection(Vector3.forward);
        float curSpeed = speed * Input.GetAxis("Vertical");
        float movementDirectionY = moveDirection.y;
        moveDirection = forward * curSpeed;

        // Jumping
        if (Input.GetButtonDown("Jump") && controller.isGrounded)
        {
            moveDirection.y = jumpSpeed;
        }
        else
        {
            moveDirection.y = movementDirectionY;
        }

        // Apply gravity. Gravity is multiplied by deltaTime twice (once here, and once below
        // when the moveDirection is multiplied by deltaTime). This is because gravity should be applied
        // as an acceleration (ms^-2)
        if (!controller.isGrounded)
        {
            moveDirection.y -= gravity * Time.deltaTime;
        }

        // Move the controller
        controller.Move(moveDirection * Time.deltaTime);
    }
}
  • Cree un nuevo script, llámelo "SC_CameraFollow" y pegue el siguiente código dentro de él:

SC_CameraFollow.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SC_CameraFollow : MonoBehaviour
{
    /*
    This camera smoothers out rotation around the y-axis and height.
    Horizontal Distance to the target is always fixed.

    There are many different ways to smooth the rotation but doing it this way gives you a lot of control over how the camera behaves.

    For every of those smoothed values we calculate the wanted value and the current value.
    Then we smooth it using the Lerp function.
    Then we apply the smoothed values to the transform's position.
    */

    // The target we are following
    public Transform target;
    // The distance in the x-z plane to the target
    public float distance = 10.0f;
    // the height we want the camera to be above the target
    public float height = 5.0f;
    // How much we 
    public float heightDamping = 2.0f;
    public float rotationDamping = 3.0f;

    void LateUpdate()
    {
        // Early out if we don't have a target
        if (!target)
            return;

        // Calculate the current rotation angles
        float wantedRotationAngle = target.eulerAngles.y;
        float wantedHeight = target.position.y + height;
        float currentRotationAngle = transform.eulerAngles.y;
        float currentHeight = transform.position.y;

        // Damp the rotation around the y-axis
        currentRotationAngle = Mathf.LerpAngle(currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);

        // Damp the height
        currentHeight = Mathf.Lerp(currentHeight, wantedHeight, heightDamping * Time.deltaTime);

        // Convert the angle into a rotation
        Quaternion currentRotation = Quaternion.Euler(0, currentRotationAngle, 0);

        // Set the position of the camera on the x-z plane to:
        // distance meters behind the target
        transform.position = target.position;
        transform.position -= currentRotation * Vector3.forward * distance;

        // Set the height of the camera
        transform.position = new Vector3(transform.position.x, currentHeight, transform.position.z);

        // Always look at the target
        transform.LookAt(target);
    }
}
  • Crea un nuevo script, llámalo "SC_SmoothFollow" y pega el siguiente código dentro de él:

SC_SmoothFollow.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SC_SmoothFollow : MonoBehaviour
{
    // The target we are following
    public Transform target;
    // The distance in the x-z plane to the target
    public float distance = 10.0f;
    // the height we want the camera to be above the target
    public float height = 5.0f;
    // How much we 
    public float heightDamping = 2.0f;
    public float rotationDamping = 3.0f;

    // Start is called before the first frame update
    void Start()
    {
        if (!target) return;

        transform.LookAt(target);
    }

    void LateUpdate()
    {
        // Early out if we don't have a target
        if (!target) return;

        // Calculate the current rotation angles
        float wantedRotationAngle = target.eulerAngles.y;
        float wantedHeight = target.position.y + height;

        float currentRotationAngle = transform.eulerAngles.y;
        float currentHeight = transform.position.y;

        // Damp the rotation around the y-axis
        currentRotationAngle = Mathf.LerpAngle(currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);

        // Damp the height
        currentHeight = Mathf.Lerp(currentHeight, wantedHeight, heightDamping * Time.deltaTime);

        // Convert the angle into a rotation
        var currentRotation = Quaternion.Euler(0, currentRotationAngle, 0);

        // Set the position of the camera on the x-z plane to:
        // distance meters behind the target
        transform.position = target.position;
        transform.position -= currentRotation * Vector3.forward * distance;

        // Set the height of the camera
        transform.position = new Vector3(transform.position.x, currentHeight, transform.position.z);

        // Always look at the target
        transform.LookAt(target);
    }
}

Paso 2: crea un personaje de gusano

El siguiente paso es crear un personaje de gusano:

  • Cree una nueva Esfera (GameObject -> Objeto 3D -> Esfera) cambie su posición a (0, 0, 0), elimine su componente SphereCollider y cámbiele el nombre a "Worm"

  • Duplica la esfera "Worm", cámbiale el nombre a "BodyPart1", cambia su posición a (0, -0,1, -0,9) y cambia su escala a (0,8, 0,8, 0,8).
  • Duplica la esfera "Worm" nuevamente, cámbiale el nombre a "BodyPart2", cambia su posición a (0, -0.2, -1.6) y cambia su escala a (0.6, 0.6, 0.6)

  • Haga clic derecho en el objeto "Worm" -> Crear vacío y cambie el nombre del objeto recién creado a "Eyes"
  • Duplica la esfera "BodyPart2", cámbiale el nombre a "Eye" y muévela dentro del objeto "Eyes", cambia su posición a (-0,24, 0,353, 0,324) y cambia su escala a (0,4, 0,4)., 0,4)
  • Duplica la esfera "Eye" y cambia su posición X a 0,24

  • Para la visualización, puedes crear algunos materiales, por ejemplo, verde para el cuerpo y azul para los ojos.

Juego de gusanos en Unity

El personaje del gusano está listo.

Paso 3: configurar el controlador de gusanos

El último paso es asignar los scripts:

  • Adjunte el script SC_CameraFollow al objeto Cámara principal y asigne la esfera "Worm" a la variable de destino:

  • Adjunte el script SC_WormController a la esfera "Worm" (automáticamente agregará otro componente llamado CharacterController):

  • Adjunte el script SC_SmoothFollow a la esfera "BodyPart1" y establezca sus valores igual que en la captura de pantalla a continuación:

  • Adjunte el script SC_SmoothFollow a la esfera "BodyPart2" y establezca sus valores igual que en la captura de pantalla a continuación:

El controlador ya está listo, usa W, A, S y D para moverte y la barra espaciadora para saltar.

El paquete fuente Unity está disponible a continuación.

Fuente
📁WormController.unitypackage40.01 KB
Artículos sugeridos
Tutorial del controlador de jugador de arriba hacia abajo para Unity
Tutorial de salto de pared 3D y 2D de Player para Unity
Tutorial de linterna para Unity
Implementación del sistema Parkour en Unity
Controlador de reproductor RTS y MOBA para Unity
Controlador de helicóptero para Unity
Controlador de coche para Unity