Reputation: 23
I made it possible for the character to walk in 8 directions, but I don’t know how to add a “jump” to make everything work...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public CharacterController controller;
public float speed;
float turnSmoothVelocity;
public float turnSmoothTime;
void Update() {
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
if (direction.magnitude >= 0.1f) {
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
transform.rotation = Quaternion.Euler(0f, angle, 0f);
controller.Move(direction * speed * Time.deltaTime);
}
}
}
Upvotes: 0
Views: 9130
Reputation: 401
There is no need to calculate the angle and the rotation of the character since these are already calculated for you by Unity when you are using the CharacterController class.
To jump, you probably need to assign a button to the jump action.Then, you can check in Update
whether your jump button is pressed for each frame.
You can use something like this and add it to the movement command in your code:
public float jumpSpeed = 2.0f;
public float gravity = 10.0f;
private Vector3 movingDirection = Vector3.zero;
void Update() {
if (controller.isGrounded && Input.GetButton("Jump")) {
movingDirection.y = jumpSpeed;
}
movingDirection.y -= gravity * Time.deltaTime;
controller.Move(movingDirection * Time.deltaTime);
}
Upvotes: 4