Unity_使用ScreenPointToWorldPointInRectangle方法使2D图片随鼠标转动

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

public class GunRoutate : MonoBehaviour
{
    //给定RectTransform平面上的位置
    public RectTransform UGUIPosition;
    //渲染的相机
    public Camera CameraMain;
    //鼠标的位置
    private Vector3 mousePos;

    // Start is called before the first frame update
    void Start()
    {
        
    }

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

        //将屏幕空间点转换为世界空间中给定RectTransform平面上的位置。
        RectTransformUtility.ScreenPointToWorldPointInRectangle(UGUIPosition, new Vector2(Input.mousePosition.x, Input.mousePosition.y), CameraMain, out mousePos);
        float z;
        if (mousePos.x > transform.position.x)
        {
            //返回 from到to的角度 不超过180度
            z = -Vector3.Angle(Vector3.up, mousePos - transform.position);
        }
        else {
            //返回 from到to的角度 不超过180度
            z = Vector3.Angle(Vector3.up, mousePos - transform.position);
        }
        //使Gun旋转
        transform.localRotation = Quaternion.Euler(0,0,z);

    }
}

猜你喜欢

转载自blog.csdn.net/weixin_42137574/article/details/106564298