1
votes

So I've been trying to get my character to move and rotate, as in the usual ways within games. This being: Moving forward at a certain speed and being able to turn the direction of the character to move into other directions.

I'm using the character controller and so far, everything has worked out. However, once I got to actually rotating the character into a different direction, it spewed out an error to me.

Error: error CS0029: Cannot implicitly convert type void' toUnityEngine.Vector3'

When I remove the Vector3 left line, it works again. So I believe it has to do with unity not wanting me to use transform.Rotate

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class basicmove : MonoBehaviour {


    public float walkSpeed;
    public float turnSpeed;


    void FixedUpdate() {
        CharacterController controller = GetComponent<CharacterController>();
        Vector3 forward = transform.TransformDirection(Vector3.forward);
        Vector3 left = transform.Rotate(Vector3.left*Time.deltaTime);

        if(Input.GetKey(KeyCode.W)){
            controller.SimpleMove(forward * walkSpeed);
        }
        if(Input.GetKey(KeyCode.A)){
            controller.SimpleMove(left * turnSpeed);
        }
    }
}
1
Transform.Rotate returns a void: docs.unity3d.com/ScriptReference/Transform.Rotate.html that is why you are getting that error.AresCaelum

1 Answers

2
votes

To turn and move at the same time there are a few things you can do, the simplest would be:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class basicmove : MonoBehaviour 
{
    public float walkSpeed;
    public float turnSpeed;
    private CharacterController controller;

    void Start() 
    {
        // Set here, so we don't have to constantly call getComponent.
        controller = getComponent<CharacterController>();
    }

    void FixedUpdate() 
    {
        if(controller != null) 
        {

            if(Input.GetKey(KeyCode.W))
            {
                // transform.forward is the forward direction of your object
                controller.SimpleMove(transform.forward * walkSpeed * Time.deltaTime);
            }

            if(Input.GetKey(KeyCode.A))
            {
                // transform.Rotate will rotate the transform using the information passed in.
                transform.Rotate(0, turnSpeed * Time.deltaTime, 0);
            }

            if(Input.GetKey(KeyCode.D))
            {
                // transform.Rotate will rotate the transform using the information passed in.
                transform.Rotate(0, -turnSpeed * Time.deltaTime, 0);
            }
        }
    }
}