using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Knife : MonoBehaviour {
private Vector3 firstPosition;
private Vector3 secondPosition;
private Vector3 middlePosition;
private LineRenderer m_LineRender;
private GameObject ray;
public Color m_Color;
public GameObject myRay;
void Start () {
m_LineRender = gameObject.AddComponent<LineRenderer>();
m_LineRender.material.color = m_Color;
m_LineRender.startWidth = 0.1f;
m_LineRender.endWidth = 0.1f;
}
void Update () {
if (Input.GetMouseButtonDown(0))
{
firstPosition = Input.mousePosition;
Debug.Log("鼠标位置 屏幕= " + firstPosition);
Debug.Log("鼠标位置 世界= " + UICamera.currentCamera.ScreenToWorldPoint(firstPosition));
m_LineRender.positionCount = 1;
m_LineRender.enabled = true;
m_LineRender.SetPosition(0, UICamera.currentCamera.ScreenToWorldPoint(Input.mousePosition));
}
if(Input.GetMouseButtonUp(0)){
secondPosition = Input.mousePosition;
m_LineRender.positionCount = 2;
m_LineRender.SetPosition(1, UICamera.currentCamera.ScreenToWorldPoint(Input.mousePosition));
middlePosition = (firstPosition + secondPosition) / 2.0f;
float angle = Mathf.Atan((secondPosition.y - firstPosition.y) / (secondPosition.x - firstPosition.x));
Debug.Log("画线位置 屏幕= " + middlePosition);
middlePosition = UICamera.currentCamera.ScreenToWorldPoint(middlePosition);
Debug.Log("画线位置 世界= " + middlePosition);
ray =Instantiate(myRay);
ray.transform.parent = this.transform;
//新生成物体 设置position 值为世界坐标系
ray.transform.position = middlePosition;
//localPosition =(父物体position-子物体position)*(屏幕高度/2)
ray.transform.localPosition = (ray.transform.position - this.transform.position) * (getHeight()/2);
ray.transform.localRotation= Quaternion.AngleAxis(angle * 180 / 3.14f, Vector3.forward);
ray.transform.localScale = this.transform.localScale;
Debug.Log("画线位置 本地= " + ray.transform.localPosition);
}
}
private int getHeight()
{
UIRoot root = GameObject.FindObjectOfType<UIRoot>();
int height = 0;
if (root != null)
{
float s = (float)root.activeHeight / Screen.height;
height = Mathf.CeilToInt(Screen.height * s);
Debug.Log("屏幕高 = " + height);
int width = Mathf.CeilToInt(Screen.width * s);
Debug.Log("屏幕宽 = " + width);
}
return height;
}
}
Unity NGUI下生成预制体坐标计算
最新推荐文章于 2024-03-19 14:33:14 发布