简体   繁体   English

如何始终将方向更改为旋转角度?

[英]How do I change my direction towards rotation angle at all times?

I have this script below and I want my player to always move towards the rotation angle, which doesn't happen.我在下面有这个脚本,我希望我的玩家总是朝着旋转角度移动,这不会发生。 It only changes direction when I click.只有当我点击时它才会改变方向。

My purpose is for the player to move at all times and towards the rotation which should be controlled by mouse position/mouse x axis (kind of like auto-run, but always change rotation based on mouse, not just move right or left).我的目的是让玩家始终移动并朝着应该由鼠标位置/鼠标 x 轴控制的旋转(有点像自动运行,但总是根据鼠标改变旋转,而不仅仅是向右或向左移动)。

I've tried about 10 different methods, nothing worked so far...我已经尝试了大约 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);

}

} }

Transform.LookAt Just get a cursor position and that's it Transform.LookAt只要得到一个 cursor position 就可以了

Vector3 direction = target.position - player.transform.position;
Quaternion finalPlayerRotation = Quaternion.LookRotation(direction);
player.transform.rotation = finalPlayerRotation;

This also works in some cases:这在某些情况下也有效:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM