- Home /
Found Answer
Moving player using character controller with new input system
Hey everyone! I've been trying to learn Unity's new input system. I prefer the character controller over using a rigid body, but it doesn't seem that there are any tutorials on using the character controller. I've tried figuring it out myself, but the player doesn't move when I press the assigned keys. I saw that it works as debug logs come out when I press the button, but for some reason, no matter what order I put the code in, the player won't move. I have the script set up properly and everything, I just need to figure out how to use the new input system with the character controller. I know that with a rigid body you can use add force, and everything works. But you can't do that with the character controller. I am using a public void outside of Update. If anyone could show me a way to do it, that'd be appreciated.
Thanks to everyone who helps!
I assume you don't need help but where is the code that you are using...
Answer by UnityPlum · Jan 28 at 11:31 PM
Alrighty, basic rundown. sideMovement will be equal to one when "D" is pressed and -1 when "A" is pressed. forwardMovement will be 1 with "W" and -1 with "S"
float sideMovement = Input.GetAxis ("Horizontal")
float forwardMovement = Input.GetAxis("Vertical")
This will tell you if the player jumped
bool canBhop = false;
bool jumped = Input.GetKeyDown (KeyCode.Space);
if (canBhop) {
jumped = Input.GetKey (KeyCode.Space);
}
And this is how you move the character:
// moveSpeed is a float
// velocity is some Vector3 with velocity
// this function will move character by x every time you call it.
GetComponent<CharacterController>().Move (velocity * moveSpeed * Time.deltaTime);
Here is a quick script I just made:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterMovement : MonoBehaviour {
public CharacterController cc;
public float moveSpeed;
public float jumpSpeed;
public float gravity;
public Vector3 velocity;
void Start()
{
cc = GetComponent<CharacterController>();
}
public void Update()
{
float sideMovement = Input.GetAxis ("Horizontal");
float forwardMovement = Input.GetAxis("Vertical");
velocity.x = sideMovement;
velocity.z = forwardMovement;
bool isGrounded = cc.isGrounded;
bool canBhop = false;
bool jumped = Input.GetKeyDown (KeyCode.Space);
if (canBhop) {
jumped = Input.GetKey (KeyCode.Space);
}
if (jumped && isGrounded)
{
velocity.y = jumpSpeed;
} else if (!isGrounded)
{
velocity.y -= gravity;
}
cc.Move ((transform.rotation * velocity) * moveSpeed * Time.deltaTime);
}
}
The user wanted the new input system. Input.GetAxis
as an example is the old, legacy system....
Follow this Question
Related Questions
unity input system help 2 Answers
Rotation of character resets when joystick is released 3 Answers
My player keeps launching into the sky 1 Answer