如何让我的角色向相机方向移动(Unity)

时间:2017-11-08 02:31:41

标签: unity3d

在Unity中,我希望这样做,以便当我握住w时,不是朝着单一方向前进,而是希望它朝我的相机方向前进,我该怎么做? (对不起,我是团结的新手)

编辑:移动脚本是:

using UnityEngine;
using System.Collections;

public class Player_Movement : MonoBehaviour {
    public float speed = 6.0F;
    public float jumpSpeed = 8.0F;
    public float gravity = 20.0F;
    private Vector3 moveDirection = Vector3.zero;
    void Update() {
        CharacterController controller = GetComponent<CharacterController>();
        if (controller.isGrounded) {
            moveDirection = new Vector3(Input.GetAxis("Horizontal"), 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);
    }
}

3 个答案:

答案 0 :(得分:0)

使用<style> #parent {background: purple; overflow: hidden;} .row {display: table; height: 300px; width: 100%} .row > div {display: table-cell; text-align: center; vertical-align: middle;} #child-left {background: red; width: 40%;} #child-right {background: blue; width: 60%;} </style> <div class="container"> <div id="parent"> <div class="row"> <div id="child-left" class="pull-left">left<br>left</div> <div id="child-right" class="pull-right">right<br>right<br>right</div> </div> <div> <div>

获取相机的前进方向

答案 1 :(得分:0)

如@lockstock所示,可以从变换中检索摄像机所面向的方向。如果您想知道如何使用它,请参阅下面的示例。

public class Player_Movement : MonoBehaviour
{
    public float speed = 6.0F;
    public float jumpSpeed = 8.0F;
    public float gravity = 20.0F;
    // Drag & Drop the camera in this field, in the inspector
    public Transform cameraTransform ;
    private Vector3 moveDirection = Vector3.zero;
    void Update() {
        CharacterController controller = GetComponent<CharacterController>();
        if (controller.isGrounded) {
            moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
            moveDirection = cameraTransform.TransformDirection(moveDirection);
            moveDirection *= speed;

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

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

此脚本正常工作,没有任何错误。我自己在Unity中测试了它。

答案 2 :(得分:0)

转动播放器,使蓝轴与相机上的蓝轴朝向相同的方向。然后将相机拖放到播放器上。现在,当您移动播放器时,摄像机将跟随并保持在播放器后面