Rotate and scale sprite based on mouse position
Hello,
I'm doing some kind of RTS and I need to scale and rotate a sprite based on mouse position. Think of it as something like a common RTS selection, where we click a point of the screen and drag to show a selection rect, but instead of the two points being the upper left corner of the rect and the bottom right, I want them to be the upper left and the upper right, and define height by other parameters (all of this is to create a formation system for units, like the one in Total War). I also want to rotate the rect based on the mouse position.
This is what I've achieved right now:
So, it is working as expected. This is the code:
private void Update()
{
if (Input.GetMouseButtonDown(1))
{
selectionStartPosition = MousePositionManager.GetMouseWorldPosition();
formationAreaGameObject.SetActive(true);
}
if (Input.GetMouseButton(1))
{
var mousePosition = MousePositionManager.GetMouseWorldPosition();
float scaleX = Vector2.Distance(mousePosition, selectionStartPosition);
formationAreaGameObject.transform.localScale = new Vector3(scaleX, 1, 1);
Vector3 centerPos = new Vector3(selectionStartPosition.x + mousePosition.x, selectionStartPosition.y + mousePosition.y) / 2;
formationAreaGameObject.transform.position = centerPos;
var rotationPosition = new Vector2(mousePosition.x - centerPos.x, mousePosition.y - centerPos.y);
var angle = Mathf.Atan2(rotationPosition.y, rotationPosition.x) * Mathf.Rad2Deg;
formationAreaGameObject.transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle));
}
if (Input.GetMouseButtonUp(1))
{
formationAreaGameObject.SetActive(false);
}
}
Now, my current problem is that I'm working on a isometric 2D tilemap scene, so I would want this "formation area" to be align with the map. To do that, it needs to be 60 degrees rotated in the X axis, so I've tried changing this line:
formationAreaGameObject.transform.rotation = Quaternion.Euler(new Vector3(60, 0, angle));
But this mess up all the other logic: the position of the rect changes when it should stay fixed to the initial mouse click position, it doesn't fully rotate to the mouse position point... And I understand why, but I really don't know how to fix the code to work with this 60 degrees variation. Can somebody help?