Skip to content

Instantly share code, notes, and snippets.

@chuwilliamson
Created March 7, 2018 21:00
Show Gist options
  • Save chuwilliamson/5c26bdfdc42f230e7b2894be5cecad57 to your computer and use it in GitHub Desktop.
Save chuwilliamson/5c26bdfdc42f230e7b2894be5cecad57 to your computer and use it in GitHub Desktop.
PlayerController to move with respect to camera
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public StringVariable Horizontal;
public StringVariable Vertical;
public StringVariable Jump;
public FloatVariable Speed;
public FloatVariable _currentSpeed;
public float gravity = 20.0F;
private Vector3 moveDirection;
private CharacterController controller;
public Vector3 targetDir;
void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
if (controller.isGrounded)
{
var h = Input.GetAxis(Horizontal.Value);
var v = Input.GetAxis(Vertical.Value);
var forward = Camera.main.transform.TransformDirection(Vector3.forward);
forward.y = 0;
forward = forward.normalized;
///such copy paste but it works
var right = new Vector3(forward.z, 0, -forward.x);
targetDir = h * right + v * forward;
if (targetDir.magnitude > 0)
transform.rotation = Quaternion.LookRotation(targetDir);
moveDirection = targetDir;
}
controller.SimpleMove(moveDirection * Speed.Value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment