rotate 2d sprite by 90 degrees on the z axis when the mouse clicks on it in unity
- User
rotate 2d sprite by 90 degrees on the z axis when the mouse clicks on it in unity
- Assistant
To rotate a 2D sprite by 90 degrees on the Z-axis when the mouse clicks on it in Unity, you can use the following steps:
-
Create a new script in Unity by right-clicking in the project window and selecting "Create > C# Script". Name it something like "SpriteRotator".
-
Open the script in your preferred code editor and add the following code:
using UnityEngine; public class SpriteRotator : MonoBehaviour { private void Update() { // Check if the mouse button is clicked if (Input.GetMouseButtonDown(0)) { // Raycast from the mouse pointer to world space Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction); // Check if the raycast hits a 2D sprite if (hit.collider != null && hit.collider.gameObject == gameObject) { // Rotate the sprite by 90 degree on the Z-axis transform.Rotate(0f, 0f, 90f); } } } } -
- User
i have multiple sprites with the script attached, but when i click on one object, all of them rotate. How do i stop that, I only want the one I click on to rotate
- Assistant
To rotate only the sprite that you click on instead of all the sprites with the script attached, you can modify the script by keeping track of the selected sprite. Here's an updated version of the script:
using UnityEngine; public class SpriteRotator : MonoBehaviour { private bool isSelected = false; private void Update() { // Check if the mouse button is clicked if (Input.GetMouseButtonDown(0)) { // Raycast from the mouse pointer to world space Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction); // Check if the raycast hits a 2D sprite if (hit.collider != null && hit.collider.gameObject == gameObject) { // Rotate the clicked sprite by 90 degrees on the Z-axis if (isSelected) { transform.Rotate(0f, 0f, 90f); } else { isSelected = true; } } else { isSelected = false; } } } }