Controlador de player planetário baseado em corpo rígido para Unity
Ao criar um controlador do jogador, a gravidade geralmente é aplicada em apenas uma direção, que é para baixo.
Mas e a gravidade com um ponto central? Este é um trabalho para o andarilho planetário.
Um andador planetário é um tipo de controlador que permite ao jogador caminhar sobre um objeto esférico (assim como os planetas), com o centro de gravidade no centro da esfera.
Passos
Abaixo estão as etapas para fazer um andador de corpo rígido planetário, com um ponto central de gravidade em Unity:
- Abra a cena com seu nível circular (no meu caso, tenho um modelo de planeta personalizado e uma Skybox personalizada na cena)
- Crie um novo script, chame-o de "SC_RigidbodyWalker" e cole o código abaixo dentro dele:
SC_RigidbodyWalker.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(CapsuleCollider))]
public class SC_RigidbodyWalker : MonoBehaviour
{
public float speed = 5.0f;
public bool canJump = true;
public float jumpHeight = 2.0f;
public Camera playerCamera;
public float lookSpeed = 2.0f;
public float lookXLimit = 60.0f;
bool grounded = false;
Rigidbody r;
Vector2 rotation = Vector2.zero;
float maxVelocityChange = 10.0f;
void Awake()
{
r = GetComponent<Rigidbody>();
r.freezeRotation = true;
r.useGravity = false;
r.collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic;
rotation.y = transform.eulerAngles.y;
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
void Update()
{
// Player and Camera rotation
rotation.x += -Input.GetAxis("Mouse Y") * lookSpeed;
rotation.x = Mathf.Clamp(rotation.x, -lookXLimit, lookXLimit);
playerCamera.transform.localRotation = Quaternion.Euler(rotation.x, 0, 0);
Quaternion localRotation = Quaternion.Euler(0f, Input.GetAxis("Mouse X") * lookSpeed, 0f);
transform.rotation = transform.rotation * localRotation;
}
void FixedUpdate()
{
if (grounded)
{
// Calculate how fast we should be moving
Vector3 forwardDir = Vector3.Cross(transform.up, -playerCamera.transform.right).normalized;
Vector3 rightDir = Vector3.Cross(transform.up, playerCamera.transform.forward).normalized;
Vector3 targetVelocity = (forwardDir * Input.GetAxis("Vertical") + rightDir * Input.GetAxis("Horizontal")) * speed;
Vector3 velocity = transform.InverseTransformDirection(r.velocity);
velocity.y = 0;
velocity = transform.TransformDirection(velocity);
Vector3 velocityChange = transform.InverseTransformDirection(targetVelocity - velocity);
velocityChange.x = Mathf.Clamp(velocityChange.x, -maxVelocityChange, maxVelocityChange);
velocityChange.z = Mathf.Clamp(velocityChange.z, -maxVelocityChange, maxVelocityChange);
velocityChange.y = 0;
velocityChange = transform.TransformDirection(velocityChange);
r.AddForce(velocityChange, ForceMode.VelocityChange);
if (Input.GetButton("Jump") && canJump)
{
r.AddForce(transform.up * jumpHeight, ForceMode.VelocityChange);
}
}
grounded = false;
}
void OnCollisionStay()
{
grounded = true;
}
}
- Crie um novo script, chame-o de "SC_PlanetGravity" e cole o código abaixo dentro dele:
SC_PlanetGravity.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SC_PlanetGravity : MonoBehaviour
{
public Transform planet;
public bool alignToPlanet = true;
float gravityConstant = 9.8f;
Rigidbody r;
void Start()
{
r = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
Vector3 toCenter = planet.position - transform.position;
toCenter.Normalize();
r.AddForce(toCenter * gravityConstant, ForceMode.Acceleration);
if (alignToPlanet)
{
Quaternion q = Quaternion.FromToRotation(transform.up, -toCenter);
q = q * transform.rotation;
transform.rotation = Quaternion.Slerp(transform.rotation, q, 1);
}
}
}
- Crie um novo GameObject e chame-o "Player"
- Crie uma nova cápsula, mova-a para dentro do objeto "Player" e mude sua posição para (0, 1, 0)
- Remova o componente Capsule Collider do Capsule
- Mova a câmera principal para dentro do objeto "Player" e mude sua posição para (0, 1.64, 0)
- Anexe o script SC_RigidbodyWalker ao objeto "Player" (você notará que ele adicionará componentes adicionais, como Rigidbody e Capsule Collider).
- Altere Capsule Collider Height para 2 e Center para (0, 1, 0)
- Atribuir câmera principal à variável da câmera do jogador em SC_RigidbodyWalker
- Por fim, anexe o script SC_PlanetGravity ao objeto "Player" e atribua seu modelo de planeta à variável Planet
Aperte o play e observe o jogador se alinhar com a superfície do planeta: