simple player 3d movement in unity code example
Example 1: 3d movement unity
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ThirdPersonMovement : MonoBehaviour
{
public CharacterController controller;
public Transform cam;
public float speed = 6f;
public float turnSmoothTime = 0.1f;
float turnSmoothVelocity;
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 + cam.eulerAngles.y;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
transform.rotation = Quaternion.Euler(0f, angle, 0f);
Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
controller.Move(moveDir.normalized * speed * Time.deltaTime);
}
}
}
Example 2: Player movement with animation unity
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Rigidbody2D rb;
private Animator anim;
private float moveSpeed;
private float dirX;
private bool facingRight = true;
private Vector3 localScale;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
localScale = transform.localScale;
moveSpeed = 3f;
}
private void Update()
{
dirX = Input.GetAxis("Horizontal") * moveSpeed;
if (Input.GetButtonDown("Jump") && rb.velocity.y > -0.1 && rb.velocity.y < 0.1)
rb.AddForce(Vector2.up * 500f);
if (Mathf.Abs(dirX) > 0 && rb.velocity.y > -0.1 && rb.velocity.y < 0.1)
{
anim.SetBool("isRunning", true);
}
else
anim.SetBool("isRunning", false);
if (rb.velocity.y > -0.1 && rb.velocity.y < 0.1)
{
anim.SetBool("isJumping", false);
anim.SetBool("isFalling", false);
}
if (rb.velocity.y > 0.1)
anim.SetBool("isJumping", true);
if (rb.velocity.y < -0.1)
{
anim.SetBool("isJumping", false);
anim.SetBool("isFalling", true);
}
}
private void FixedUpdate()
{
rb.velocity = new Vector2(dirX, rb.velocity.y);
}
private void LateUpdate()
{
if (dirX > 0)
facingRight = true;
else if (dirX < 0)
facingRight = false;
if (((facingRight) && (localScale.x < 0)) || ((!facingRight) && (localScale.x > 0)))
localScale.x *= -1;
transform.localScale = localScale;
}
}