【问题标题】:Unity: Error given when trying to change the rotation of gameobjectUnity:尝试更改游戏对象的旋转时出错
【发布时间】:2018-05-01 13:30:10
【问题描述】:

所以我一直试图让我的角色移动和旋转,就像在游戏中通常的方式一样。这就是:以一定的速度向前移动,并且能够将角色的方向转向其他方向。

我正在使用角色控制器,到目前为止,一切都已解决。但是,一旦我将角色实际旋转到不同的方向,它就会向我吐出一个错误。

错误:错误 CS0029:无法隐式转换类型 void' toUnityEngine.Vector3'

当我删除 Vector3 左行时,它再次起作用。所以我相信这与团结不希望我使用 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);
        }
    }
}

【问题讨论】:

  • Transform.Rotate 返回void:docs.unity3d.com/ScriptReference/Transform.Rotate.html 这就是您收到该错误的原因。

标签: unity3d


【解决方案1】:

要同时转动和移动,您可以做几件事,最简单的是:

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);
            }
        }
    }
}

【讨论】:

  • 谢谢,但它说控制器在当前上下文中不存在。所以我相信它看不到在 Start 中制作的控制器?
  • @Redshade 我只是将它设置为开始。我更新了代码以修复该错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多