Hi! I have this code in an open basic world. With this script I’m able to move my character in all directions. I’m new in this and I would like to know how would you improve it.
Thanks!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EmMoc : MonoBehaviour
{
private Vector3 posi;
bool jump;
private Rigidbody rb; // Agregamos un componente Rigidbody para manejar la física
private Transform cameraTransform; // Referencia a la transformación de la cámara
public float jumpForce = 2f; // Controla la fuerza del salto
public float movementSpeed = 4f; // Controla la velocidad de movimiento
public AudioClip oh;
// Start is called before the first frame update
void Start()
{
posi = new Vector3(0, 2f, 0);
jump = false;
// Obtén el componente Rigidbody
rb = GetComponent<Rigidbody>();
// Obtén la transformación de la cámara
Camera mainCamera = Camera.main;
if (mainCamera != null)
{
cameraTransform = mainCamera.transform;
}
GetComponent<AudioSource> ().playOnAwake = false;
GetComponent<AudioSource> ().clip = oh;
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Terre")
{
jump = true;
}
if (collision.gameObject.tag == "Caps")
{
GetComponent<AudioSource> ().Play ();
// Get the Renderer component from the new cube
var cubeRenderer = GetComponent<Renderer>();
// Create a new RGBA color using the Color constructor and store it in a variable
Color customColor = new Color(0.4f, 0.9f, 0.7f, 1.0f);
// Call SetColor using the shader property name "_Color" and setting the color to the custom color you created
cubeRenderer.material.SetColor("_Color", customColor);;
}
}
// Update is called once per frame
void Update()
{
// Movimiento horizontal
float horizontalInput = Input.GetAxis("Horizontal"); // Obtén la entrada horizontal (A y D)
float verticalInput = Input.GetAxis("Vertical"); // Obtén la entrada vertical (W y S)
// Transforma los inputs de acuerdo con la rotación de la cámara
Vector3 cameraForward = cameraTransform.forward;
Vector3 cameraRight = cameraTransform.right;
cameraForward.y = 0; // Elimina la componente vertical para mantenerse en el plano horizontal
cameraRight.y = 0; // Elimina la componente vertical
Vector3 moveDirection = (cameraForward.normalized * verticalInput + cameraRight.normalized * horizontalInput) * movementSpeed;
rb.velocity = new Vector3(moveDirection.x, rb.velocity.y, moveDirection.z);
// Mantén la rotación constante en los ejes Z y Y
transform.eulerAngles = new Vector3(0, transform.eulerAngles.y, 0);
// Si presionas la tecla "W" o la flecha arriba y el personaje está en el suelo, aplica un impulso en el eje Z
if (Input.GetKeyDown(KeyCode.Space) && jump)
{
rb.AddForce(posi * jumpForce, ForceMode.Impulse);
jump = false;
}
}
}