Facebook
From HEWKEW, 5 Years ago, written in C.
This paste is a reply to Movement TDS Simple Scripting from HEWKEW - view diff
Embed
Download Paste or View Raw
Hits: 412
  1. public class Controller : MonoBehaviour { // Made by HEWKEW
  2.         public float speed = 4;
  3.         private CharacterController controller;
  4.  
  5.         private void Start() {
  6.                 //We need a controller. This will let us access to very useful functions.
  7.                 controller = GetComponent<CharacterController>();
  8.         }
  9.  
  10.         private void Update() {
  11.                 //We start our functions and keep them running.
  12.                 Move();
  13.                 Rotate();
  14.         }
  15.  
  16.         private void Move()
  17.         {
  18.                 //We need a Vector3 to storage our input horizontal for our x axis and vertical for our z axis. The y axis
  19.                 //Is not needed because we won't move our object vertically.
  20.                 Vector3 movement = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
  21.                 //Since movement has inputs with maximun 1 and minimun -1, we multiply it to our speed. For example:
  22.                 //Speed: 4 ==> Movement (1, 0, or -1) * Speed = (4, 0, -4)
  23.                 controller.SimpleMove(speed * movement);
  24.         }
  25.  
  26.         private void Rotate()
  27.         {
  28.                 //Ray from the main camera to the mouse position.
  29.                 Ray _ray = Camera.main.ScreenPointToRay(Input.mousePosition);
  30.                 //New plane (not a real plane) to get the raycast.
  31.                 Plane _plane = new Plane(Vector3.up, Vector3.zero);
  32.                 //Distance from the center of the plane to the raycast (position 0 + distance from it to the hit)
  33.                 float distance;
  34.  
  35.                 if(_plane.Raycast(_ray, out distance))
  36.                 {
  37.                         //We wont need to rotate our character to look to the ground. So we need a new Vector3 to ignore it.
  38.                         Vector3 point = new Vector3(_ray.GetPoint(distance).x, transform.position.y, _ray.GetPoint(distance).z);
  39.                         //Then, we look at that point.
  40.                         transform.LookAt(point);
  41.                 }
  42.         }
  43. }
  44.