How do I make the player rotate left and right with the A and D keys?
Because I'm new and so many tutorials and forums I tried haven't worked, I've come here to ask the community for help.
What I would like to do is to make the player rotate left when A is pressed and right when D is pressed. In the past when I try this, it also alters the W and D key(which I have just fixed.
This is my current code for the player:
using UnityEngine;
using System.Collections;
public class KalusBeta : MonoBehaviour
{
private CharacterController controller;
private float verticalVelocity;
private float gravity = 14.0f;
private float jumpForce = 10.0f;
private void Start()
{
controller = GetComponent<CharacterController>();
}
private void Update()
{
if (controller.isGrounded)
{
verticalVelocity = -gravity * Time.deltaTime;
if (Input.GetKeyDown (KeyCode.Space))
{
verticalVelocity = jumpForce;
transform.Translate(0,0.6f,0);
}
}
else
{
verticalVelocity -= gravity * Time.deltaTime;
}
Vector3 moveVector = Vector3.zero;
moveVector.x = Input.GetAxis("Vertical") * +40.0f;
moveVector.y = verticalVelocity;
moveVector.z = Input.GetAxis("Horizontal") * -40.0f;
controller.Move (moveVector * Time.deltaTime);
}
}
The transform.Translate(0,0.6f,0); is something I'm using to try and make the player fly(which also isn't working and is in another question focusing on that issue) but the main focus is getting the player to rotate left and right with A and D.
In the past when I've tried tutorials and others codes, it also affected the W and S inputs so they go sideways instead of forward or backwards, so again I thought I would ask the community for help on this topic :)
You need to make your player move relative to its forward vector. That's why you were moving sideways after rotating before. I'll try to answer this in more depth tomorrow.
Answer by SohailBukhari · Mar 29, 2017 at 07:22 AM
Use This Script to move and rotate smoothly of your character controller.
If You Need More Help then Read This Documentation
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(CharacterController))]
public class RotatePlayer : MonoBehaviour
{
public float Speed = 3.0F;
public float RotateSpeed = 3.0F;
void Update()
{
CharacterController controller = GetComponent<CharacterController>();
if (transform != null)
{
transform.Rotate(0, Input.GetAxis("Horizontal") * RotateSpeed, 0);
var forward = transform.TransformDirection(Vector3.forward);
float curSpeed = Speed * Input.GetAxis("Vertical");
controller.SimpleMove(forward * curSpeed);
}
}
}