Canvas 未对齐?
Canvas Misaligned?
我按照本教程 https://www.youtube.com/watch?v=vsdIhyLKgjc 编写了这段代码:
public class DrawRect : MonoBehaviour {
[SerializeField]
public RectTransform rect;
private Vector3 startPos;
private Vector3 endPos;
void Start () {
rect.gameObject.SetActive (false);
}
void Update () {
if (Input.GetMouseButtonDown(0)) {
RaycastHit hit;
if (Physics.Raycast (Camera.main.ScreenPointToRay (Input.mousePosition), out hit, Mathf.Infinity)) {
startPos = hit.point;
}
}
if (Input.GetMouseButtonUp(0)) {
rect.gameObject.SetActive (false);
}
if (Input.GetMouseButton (0)) {
if (!rect.gameObject.activeInHierarchy) {
rect.gameObject.SetActive (true);
}
endPos = Input.mousePosition;
Vector3 squareStart = Camera.main.WorldToScreenPoint (startPos);
squareStart.z = 0f;
Vector3 center = (squareStart + endPos / 2f);
rect.position = center;
float sizeX = Mathf.Abs (squareStart.x - endPos.x);
float sizeY = Mathf.Abs (squareStart.y - endPos.y);
rect.sizeDelta = new Vector2 (sizeX, sizeY);
}
}
}
问题是每当我使用它时,它都会错位。比例是正确的,但 startpos 和 endpos 总是屏幕的 1/3 太远,有点偏右。否则 endpos 会完美地跟随我的鼠标,与我实际的鼠标保持不对齐。
非常感谢任何有助于找出问题的帮助。
如果我对问题的解释不好,尽管问。
你链接的教程中的答案是逐字逐句的,你为什么要在这里问你的问题?
Vector3 center = (squareStart + endPos / 2f);
除法优先于括号。
Vector3 center = (squareStart + endPos) / 2f;
我按照本教程 https://www.youtube.com/watch?v=vsdIhyLKgjc 编写了这段代码:
public class DrawRect : MonoBehaviour {
[SerializeField]
public RectTransform rect;
private Vector3 startPos;
private Vector3 endPos;
void Start () {
rect.gameObject.SetActive (false);
}
void Update () {
if (Input.GetMouseButtonDown(0)) {
RaycastHit hit;
if (Physics.Raycast (Camera.main.ScreenPointToRay (Input.mousePosition), out hit, Mathf.Infinity)) {
startPos = hit.point;
}
}
if (Input.GetMouseButtonUp(0)) {
rect.gameObject.SetActive (false);
}
if (Input.GetMouseButton (0)) {
if (!rect.gameObject.activeInHierarchy) {
rect.gameObject.SetActive (true);
}
endPos = Input.mousePosition;
Vector3 squareStart = Camera.main.WorldToScreenPoint (startPos);
squareStart.z = 0f;
Vector3 center = (squareStart + endPos / 2f);
rect.position = center;
float sizeX = Mathf.Abs (squareStart.x - endPos.x);
float sizeY = Mathf.Abs (squareStart.y - endPos.y);
rect.sizeDelta = new Vector2 (sizeX, sizeY);
}
}
}
问题是每当我使用它时,它都会错位。比例是正确的,但 startpos 和 endpos 总是屏幕的 1/3 太远,有点偏右。否则 endpos 会完美地跟随我的鼠标,与我实际的鼠标保持不对齐。
非常感谢任何有助于找出问题的帮助。
如果我对问题的解释不好,尽管问。
你链接的教程中的答案是逐字逐句的,你为什么要在这里问你的问题?
Vector3 center = (squareStart + endPos / 2f);
除法优先于括号。
Vector3 center = (squareStart + endPos) / 2f;