Hi!
First of all, I dont want to use the FPS Controller Prefab and a C# script (peace hahaha)
So how do I move my character to go forward where Im currently looking at.
Thnks!
Hi!
First of all, I dont want to use the FPS Controller Prefab and a C# script (peace hahaha)
So how do I move my character to go forward where Im currently looking at.
Thnks!
int speed = 10;
void Move()
{
Vector3 moveVec = new Vector3( Input.GetAxis("Horizontal") , 0 , Input.GetAxis("Vertical") );
player.transform.position += moveVec * speed * Time.DeltaTime;
}
Make sure the Project Settings
→ Input
has "Horizontal"
and "Vertical"
axes assigned to WASD/ Arrow keys.
Here is my code with character controller. It doesn’t have gravity by default so I added it. I assume you want it for a 3d game
public float speed = 5;
public float gravity = -5;
float velocityY = 0;
CharacterController controller;
void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
velocityY += gravity * Time.deltaTime;
Vector3 input = new Vector3(Input.GetAxisRaw("Horizontal"), 0 Input.GetAxisRaw("Vertical"));
input = input.normalized;
Vector3 temp = Vector3.zero;
if (input.z == 1)
{
temp += transform.forward;
}
else if (input.z == -1)
{
temp += transform.forward * -1;
}
if (input.x == 1)
{
temp += transform.right;
}
else if (input.x == -1)
{
temp += transform.right * -1;
}
Vector3 velocity = temp * speed;
velocity.y = velocityY;
controller.Move(velocity * Time.deltaTime);
if (controller.isGrounded)
{
velocityY = 0;
}
}
This will also work with a controller. The main advantage of using a character controller over rigidbody is it can go up slopes.
Also, if you want jumping, it’s simple enough, the axis is Input.GetAxisRaw(“Jump”), and just reset velocityY to how far you want to jump
Try this:
void Update()
{
Rigidbody rb = GetComponent<Rigidbody>();
if (Input.GetKey(KeyCode.A)) rb.AddForce(Vector3.left);
if (Input.GetKey(KeyCode.D)) rb.AddForce(Vector3.right);
if (Input.GetKey(KeyCode.W)) rb.AddForce(Vector3.up);
if (Input.GetKey(KeyCode.S)) rb.AddForce(Vector3.down);
}
Don’t forget to attach a Rigidbody
to your object and make sure script is attached to object that is going to move.