Reputation: 63
I followed this tutorial https://www.youtube.com/watch?v=vsdIhyLKgjc and wrote this code:
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);
}
}
}
The problem being that whenever I use it, it's misaligned. The scale is correct but the startpos and endpos are always 1/3 of the screen too far up and a bit to the right. Otherwise the endpos follows my mouse perfectly, staying misaligned to my actual mouse.
Any help with finding out the problem is greatly appreciated.
If I explained the problem poorly, just ask.
Upvotes: 0
Views: 60
Reputation: 94
Why are you asking your question here when the answer is verbatim in the tutorial you linked?
Vector3 center = (squareStart + endPos / 2f);
Division takes precedence over the brackets.
Vector3 center = (squareStart + endPos) / 2f;
Upvotes: 1