- Home /
Inconsistent Mouse Related Behavior in 2D
I'm attempting to follow a tutorial to add RTS selection box functionality to my game. However the behavior I'm seeing is very different than what was demonstrate in the tutorial despite my best efforts to stay in sync. Below is my code, I've attached it to an empty game object that is active in my scene.
public class UnitSelection : MonoBehaviour
{
public RectTransform selectionBox;
private Vector2 startClickPos;
// Update is called once per frame
void Update()
{
//Left Mouse Down
if (Input.GetMouseButtonDown(0))
{
startClickPos = Input.mousePosition;
selectionBox.transform.position = new Vector2(startClickPos.x, startClickPos.y);
}
//Left Mouse Held Down
if (Input.GetMouseButton(0))
{
UpdateSelectionBox(Input.mousePosition);
}
//Let Mouse Up
if (Input.GetMouseButtonUp(0))
{
}
}
void UpdateSelectionBox(Vector2 curMousePos)
{
if (selectionBox.gameObject.activeInHierarchy)
{
selectionBox.gameObject.SetActive(true);
}
float newWidth = curMousePos.x - startClickPos.x;
float newHeight = curMousePos.y - startClickPos.y;
selectionBox.sizeDelta = new Vector2(Mathf.Abs(newWidth), Mathf.Abs(newHeight));
selectionBox.anchoredPosition = startClickPos + new Vector2(newWidth / 2, newHeight / 2);
}
}
My selectionBox object inspector view is also there. Please let me know if there's anything else that would be helpful. Here is a gif of the behavior.
Answer by karoly · May 14, 2020 at 04:24 AM
So I actually managed to figure this out on my own after creating a completely empty project with just a UI Image object and my basic box drawing script.
The issue was that the Canvas UI scaler I had was set to "Scale with Screen Size" which was causing all sorts of issues with the click and drag. I switched it to "Constant Pixel Size" and my code worked exactly as expected.
I've submitted a bug report with the basic project and instructions because there is no way this is working as intended.