Tutorial 3D Worm Controller pentru Unity

În acest tutorial, voi arăta cum să creați un controler de vierme simplu în Unity, inspirat din seria de tutoriale pentru dezvoltarea jocurilor pentru începători TornadoTwins.

Controlerul de vierme se va aluneca în jur cu un efect neted de urmărire a cozii și va avea capacitatea de a sări.

Scripturile din acest tutorial au fost scrise inițial în JavaScript (alias UnityScript), care nu mai este acceptat, așa că voi oferi o alternativă C#.

Sharp Coder Video player

Pentru a crea un controler de vierme în Unity vom avea nevoie de:

  • Creați scripturile necesare
  • Creați un personaj vierme
  • Atribuiți scenariile personajului

Pasul 1: Creați toate scripturile necesare

Să începem prin a crea toate scripturile care vor fi necesare pentru a configura un controler de vierme:

  • Creați un nou script, numiți-l "SC_WormController" și inserați codul de mai jos în el:

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);
    }
}
  • Creați un nou script, numiți-l "SC_CameraFollow" și inserați codul de mai jos în el:

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ți un nou script, numiți-l "SC_SmoothFollow" și inserați codul de mai jos în el:

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);
    }
}

Pasul 2: Creați un personaj vierme

Următorul pas este crearea unui personaj vierme:

  • Creați o nouă sferă (GameObject -> 3D Object -> Sphere) schimbați-i poziția în (0, 0, 0), ștergeți componenta SphereCollider și redenumiți-o în "Worm"

  • Duplicați sfera "Worm", redenumiți-o în "BodyPart1", schimbați-i poziția în (0, -0.1, -0.9) și schimbați-i scara la (0.8, 0.8, 0.8)
  • Duplicați din nou sfera "Worm", redenumiți-o în "BodyPart2", schimbați-i poziția în (0, -0.2, -1.6) și schimbați-i scara la (0.6, 0.6, 0.6)

  • Faceți clic dreapta pe obiectul "Worm" -> Create Empty și redenumiți obiectul nou creat în "Eyes"
  • Duplicați sfera "BodyPart2", redenumiți-o în "Eye" și mutați-o în interiorul obiectului "Eyes", schimbați-i poziția în (-0.24, 0.353, 0.324) și schimbați-i scala în (0.4, 0.4, 0.4)
  • Duplicați sfera "Eye" și schimbați-i poziția X la 0,24

  • Pentru vizualizare, puteți crea câteva materiale, de exemplu, verde pentru corp și albastru pentru ochi.

Jocul viermilor în Unity

Personajul Vierme este gata.

Pasul 3: Configurați controlerul vierme

Ultimul pas este alocarea scripturilor:

  • Atașați scriptul SC_CameraFollow la obiectul Camera principală și atribuiți sfera "Worm" variabilei țintă:

  • Atașați scriptul SC_WormController la sfera "Worm" (va adăuga automat o altă componentă numită CharacterController):

  • Atașați scriptul SC_SmoothFollow la sfera "BodyPart1" și setați-i valorile la fel ca în screenshot de mai jos:

  • Atașați scriptul SC_SmoothFollow la sfera "BodyPart2" și setați-i valorile la fel ca în screenshot de mai jos:

Controlerul este acum gata, utilizați W, A, S și D pentru a vă deplasa și spațiu pentru a sari.

Pachetul sursă Unity este disponibil mai jos.

Sursă
📁WormController.unitypackage40.01 KB
Articole sugerate
Player 3D și 2D Wall Jump Tutorial pentru Unity
Tutorial de sus în jos pentru controlerul jucătorului pentru Unity
Tutorial lanternă pentru Unity
Cum să adăugați suport pentru platforma în mișcare la controlerul de caractere în Unity
Adăugarea suportului pentru salt dublu la un controler de caractere 2D platformer în Unity
Controler de jucător RTS și MOBA pentru Unity
Controler de elicopter pentru Unity