Search Unity

Adjusting CharacterController.Move to allow rotation using the horizontal axis

Discussion in 'Scripting' started by KBurchfiel, May 29, 2016.

  1. KBurchfiel

    KBurchfiel

    Joined:
    May 16, 2016
    Posts:
    7
    Hi everyone, I'm very new to Unity but am excited to try working on a 3D Platformer/Collectathon.

    I originally gave a rigidbody to my character and added raycasting to limit the times he could jump, but I decided to transition to a character controller. I like the CharacterController.Move script (http://docs.unity3d.com/ScriptReference/CharacterController.Move.html ), but it uses the horizontal axis for strafing, and I wanted to use it for rotation instead. Here's how I modified it. (Note that I allow the character to rotate in the air.)

    It's working alright for me so far, but if you have any questions or suggestions feel free to share them. Again, I'm very new to Unity and programming!

    using UnityEngine;
    using System.Collections;

    public class CharacterControllerScript : MonoBehaviour {


    public float speed = 6.0F;
    public float jumpSpeed = 8.0F;
    public float gravity = 20.0F;
    public float rotateSpeed = 3.0F;
    private Vector3 moveDirection = Vector3.zero;
    void Update()
    {
    CharacterController controller = GetComponent<CharacterController>();

    transform.Rotate(0, Input.GetAxis("Horizontal") * rotateSpeed * Time.deltaTime, 0);
    if (controller.isGrounded)
    {
    moveDirection = new Vector3(0, 0, Input.GetAxis("Vertical"));
    moveDirection = transform.TransformDirection(moveDirection);
    moveDirection *= speed;

    if (Input.GetButton("Jump"))
    moveDirection.y = jumpSpeed;

    }
    moveDirection.y -= gravity * Time.deltaTime;
    controller.Move(moveDirection * Time.deltaTime);
    }
    }
     
  2. crispybeans

    crispybeans

    Joined:
    Apr 13, 2015
    Posts:
    210
    can't you use sometihng like this to get the "left/right" to get the direction of which to strafe ?

    Code (CSharp):
    1.  
    2. Transform tf = this.transform;
    3. Vector3 left = Vector3.Dot( tf.forward, tf.up );
    4. Vector3 right = left * -1f;                      
    5.