【问题标题】:Need a way for player to move towards the direction the camera is pointing. (Unity)需要一种方式让玩家朝着摄像机指向的方向移动。 (统一)
【发布时间】:2021-10-28 05:34:45
【问题描述】:

我是一名初级程序员,通过编写一些第三人称动作脚本开始练习。对于相机,我使用了 Cinemachine 的 Free Look 相机,但我遇到了问题。玩家有一个向前的方向,但我希望这个方向改变到玩家面对的任何地方。我查找了一些不同的东西,但没有一个在我的代码中起作用。任何帮助,将不胜感激。 C#。 (抱歉,并非所有代码都会进入。)

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

public class CapsuleMovement : MonoBehaviour
{
    public float speed = 10f;
    public Rigidbody rb;
    public bool BeanOnTheGround = true;

    private void start() {
        rb = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        float horizontal = Input.GetAxis("Horizontal") * Time.deltaTime * speed;
        float vertical = Input.GetAxis("Vertical") * Time.deltaTime * speed;


        transform.Translate(horizontal, 0, vertical);

        if(Input.GetButtonDown("Jump") && BeanOnTheGround) {
            rb.AddForce(new Vector3(0, 5, 0), ForceMode.Impulse);
            BeanOnTheGround = false;
        }
    }

    private void OnCollisionEnter(Collision collision) {
        if(collision.gameObject.tag == "Ground") {
            BeanOnTheGround = true;
        }
    }
}

【问题讨论】:

  • 几个问题? 1.-您是否尝试在所示脚本中的某处设置旋转? 2.- 您要设置旋转的游戏对象是附有CapsuleMovement 的游戏对象,是吗?

标签: c# unity3d scripting 3d


【解决方案1】:

根据Quaternion.LookRotation

我会尝试:

transform.rotation = Quaternion.LookRotation(Camera.main.transform.forward, Camera.main.transform.up);

对于要设置旋转的游戏对象的变换。 例如,附加此脚本的游戏对象将在Start 时间面向主摄像机的前方。

using UnityEngine;

public class LookToCamForward : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        transform.rotation = Quaternion.LookRotation(Camera.main.transform.forward, Camera.main.transform.up);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-23
    • 1970-01-01
    相关资源
    最近更新 更多