首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Navmesh随鼠标旋转

Navmesh随鼠标旋转
EN

Stack Overflow用户
提问于 2020-09-30 19:18:56
回答 1查看 520关注 0票数 0

我想旋转我的NavigationMeshAgent参照鼠标的位置。下面是我这样做的代码。

代码语言:javascript
复制
public class Navcontroller : MonoBehaviour
{
    // Start is called before the first frame update

    private NavMeshAgent _agent;
    void Start()
    {
        _agent = GetComponent<NavMeshAgent>();
    }

    // Update is called once per frame
    void Update()
    {
        
        float horInput = Input.GetAxis("Horizontal");
        float verInput = Input.GetAxis("Vertical");
        
        Vector3 movement = new Vector3(horInput, 0f, verInput);
        Vector3 moveDestination = transform.position + movement;
        _agent.destination = moveDestination;

    }
}

不巧的是,旋转是奇怪的,当我移动鼠标的时候,它可以看遍整个地方。我遗漏了什么?

更新:

我已经用鼠标的位置更新了我的代码如下,

代码语言:javascript
复制
public class Navcontroller : MonoBehaviour

{

// Start is called before the first frame update

private NavMeshAgent _agent;
float mouseX, mouseY;
float rotationSpeed = 1;

void Start()
{
    _agent = GetComponent<NavMeshAgent>();
    
    Cursor.visible = false;
    Cursor.lockState = CursorLockMode.Locked;

}

// Update is called once per frame
void Update()
{
    

    float horInput = Input.GetAxis("Horizontal");
    float verInput = Input.GetAxis("Vertical");
    
    Vector3 movement = new Vector3(horInput, 0f, verInput);
    Vector3 moveDestination = transform.position + movement ;
    
    mouseX += Input.GetAxis("Mouse X") * rotationSpeed;
    mouseY -= Input.GetAxis("Mouse Y") * rotationSpeed;
    
    _agent.destination = moveDestination;

    _agent.transform.rotation = Quaternion.Euler(mouseY, mouseX, 0);

}

}

现在代理和相机一起旋转。但这名特工并没有朝他所看到的方向移动。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-30 19:54:42

基于评论

代码语言:javascript
复制
Vector3 mousePosition = Input.mousePosition; // Get mouse position
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition); //Transfom it to game space - form screen space
Vector2 direction = new Vector2(
mousePosition.x - transform.position.x,
mousePosition.y - transform.position.y
); // create new direction

transform.up = direction; // Rotate Z axis

因为基于评论,这与NavigationMeshAgent或AI无关。那么,要向前迈进,你要做的

代码语言:javascript
复制
if(Input.GetKey(Key.W)){
    transform.forward += Speed * Time.deltaTime;
}

编辑

您的_agent.destination = moveDestination;需要匹配您的旋转,所以您需要乘以它的旋转。_agent.destination = Quaternion.Euler(mouseY, mouseX, 0) * moveDestinationmoveDestination应该相对于它的旋转(不是像现在这样绝对的),所以最好使用_agent.destination = Quaternion.Euler(mouseY, mouseX, 0) * Vector3.forward

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64144375

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档