【问题标题】:How do I change my direction towards rotation angle at all times?如何始终将方向更改为旋转角度?
【发布时间】:2020-12-31 10:06:04
【问题描述】:

我在下面有这个脚本,我希望我的播放器始终朝着旋转角度移动,但这不会发生。只有当我点击时它才会改变方向。

我的目的是让玩家始终移动并朝着应该由鼠标位置/鼠标 x 轴控制的旋转(有点像自动运行,但总是根据鼠标改变旋转,而不仅仅是向右移动或左)。

我已经尝试了大约 10 种不同的方法,到目前为止都没有奏效......

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

public class MovementController : MonoBehaviour
{
public float speed = 4;
public float rot = 0f;
public float rotSpeed = 80;
public float gravity = 8;

private Camera cam;
Vector3 moveDir = Vector3.zero;

CharacterController controller;
Animator anim;

// Start is called before the first frame update
void Start()
{
controller = GetComponent<CharacterController> ();
anim = GetComponent<Animator>();

}


// Update is called once per frame
void Update()
{
           
 
 float horizontalSpeed = 8.0f;
 //Get the mouse delta. This is not in the range -1...1
 float h = horizontalSpeed * Input.GetAxis("Mouse X");
 float z = horizontalSpeed * Input.GetAxis("Mouse Y");
 transform.Rotate(0, h, 0);

  //Move Input
    
  if(controller.isGrounded){
  if(Input.GetMouseButtonUp(1))
  {
            
    
   anim.SetInteger ("condition", 1);
   moveDir = new Vector3 (0,0,1) * speed;

   // moveDir *= speed;
   moveDir = transform.TransformDirection(moveDir);

            
    }

    if(Input.GetMouseButtonDown(1))
    {
    anim.SetInteger("condition", 0);
    moveDir = Vector3.zero;
    }

    
    }

   

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

}

}

【问题讨论】:

  • 简单看看!

标签: c# unity3d game-physics


【解决方案1】:

Transform.LookAt 只需获取光标位置即可

【讨论】:

  • 没有真正的工作。也许我做错了,transform.LookAt到底是什么?我试图让一条射线来获取鼠标位置,我不能只在 x 轴上查看 input.mouseposition,所以它只是在错误的轴上旋转我的 plaer 并且从不移动。我无法将moveDir 向量更改为任何有用的...
【解决方案2】:
Vector3 direction = target.position - player.transform.position;
Quaternion finalPlayerRotation = Quaternion.LookRotation(direction);
player.transform.rotation = finalPlayerRotation;

这在某些情况下也有效:

Vector3 direction = target.position - player.transform.position;
player.transform.right /*You may need to change the Right to upper, -upper, -Right depend on the player rotation and the target position*/ = direction;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多