- Home /
Is my controller script good?
This is my first code in C#, Is it good? I used RigidBody to get better collisions. using System.Collections; using System.Collections.Generic; using UnityEngine;
public class movimento : MonoBehaviour
{
public Rigidbody rigid;
public float VelocidadeAtual, VelocidadeSprint;
// Start is called before the first frame update
void Start()
{
rigid = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKey("w"))
{
rigid.AddForce(transform.forward * VelocidadeAtual, ForceMode.Acceleration);
}
if (Input.GetKey("s"))
{
rigid.AddForce(transform.forward * -VelocidadeAtual, ForceMode.Acceleration);
}
if (Input.GetKey("a"))
{
rigid.AddForce(transform.right * -VelocidadeAtual, ForceMode.Acceleration);
}
if (Input.GetKey("d"))
{
rigid.AddForce(transform.right * VelocidadeAtual, ForceMode.Acceleration);
}
if (Input.GetKey(KeyCode.LeftShift))
{
VelocidadeAtual = VelocidadeSprint;
}
if (Input.GetKeyUp(KeyCode.LeftShift))
{
VelocidadeAtual = 10;
}
}
}
Answer by Xamtox · Dec 11, 2019 at 07:24 AM
I can think of several improvements:
Class name
movimento
should start with capital letter.Component initialization is better to move to
Awake()
instead ofStart()
. It's irrelevant in your case, but better practice in general.Instead of
public
is better to use[SerializeField] private
. Then you still can configure your values via inspector, but cannot mess with your variables outside the script.You could combine horizontal ('a' and 'd') and vertical ('w' and 's') movements, and sprint logic can be written in single line.
Example:
private Rigidbody rigid;
[SerializeField] private VelocidadeSprint = 20;
[SerializeField] private VelocidadeAtual = 10;
void Awake()
{
rigid = GetComponent<Rigidbody>();
}
void Update()
{
float speed = Input.GetKey(KeyCode.LeftShift) ? VelocidadeSprint : VelocidadeAtual;
Vector3 forward = Input.GetAxis("Vertical") * transform.forward;
Vector3 sideways = Input.GetAxis("Horizontal") * transform.right;
rigid.AddForce((forward + sideways) * speed, ForceMode.Acceleration);
}
In that case speed will always be 20 when shift key is pressed and 10 otherwise.
Also, you could use [RequireComponent(typeof(Rigidbody))]
attribute on your movimento
class to ensure there always will be a Rigidbody.
Your answer
![](https://koobas.hobune.stream/wayback/20220612220015im_/https://answers.unity.com/themes/thub/images/avi.jpg)