In Unity, how to get the current object to get the mouse position and turn it to the mouse position on the screen?

introduce

In Unity, how to get the current object to get the mouse position and turn it to the mouse position on the screen?


method

void Update() {
    
    
    // 获取鼠标在屏幕上的位置
    Vector3 mousePos = Input.mousePosition;

    // 将鼠标在屏幕上的位置转换为世界空间中的位置
    Vector3 worldPos = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, Camera.main.transform.position.z));

    // 计算物体需要朝向的方向
    Vector3 direction = (worldPos - transform.position).normalized;

    // 使用LookRotation方法将物体朝向鼠标的位置
    transform.rotation = Quaternion.LookRotation(direction, Vector3.up);
}


void Update() {
    
    
    // 获取鼠标在屏幕上的位置
    Vector3 mousePos = Input.mousePosition;

    // 将鼠标在屏幕上的位置转换为世界空间中的位置
    Vector3 worldPos = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, Camera.main.transform.position.z));

    // 计算物体需要朝向的方向
    Vector3 direction = (worldPos - transform.position).normalized;

    // 使用LookRotation方法将物体朝向鼠标的位置
    transform.rotation = Quaternion.LookRotation(direction, Vector3.up);
}


Insert image description here


Guess you like

Origin blog.csdn.net/qq_20179331/article/details/130479627
Recommended