Hi! I want to make a 2D game where you can interact with on-screen objects, but i don’t know how to rotate a object with mouse, in a circular movement, and with some angle limits. Here’s an example of a door handle:
Korridorer | MONSTERER - YouTube Minute 1:48.
You can’t rotate it upwards, and the rotation is smooth, not following the exact position of the mouse, like it has weight or something.
Any idea how to achieve this effect?
Thank you everyone!
Script i made, put a handle with the script attached to that, the handle must have a parent that it will rotate around
HandlePivot: Parent
- Clamp, how far the handle can rotate, once the handle reaches the y value the door will open
- speed: how fast the handle rotates
- Weight: How Heavy the handle is
using UnityEngine;
using UnityEngine.EventSystems;
public class Handle : MonoBehaviour, IDragHandler, IPointerDownHandler, IPointerUpHandler, IPointerEnterHandler, IPointerExitHandler
{
public Transform HandlePivot;
public Vector2 HandlePosClamp = new Vector2(0,70);
public float Speed = 125;
public float Weight = 175;
bool isDraging;
bool isOver;
private void FixedUpdate()
{
var distance = Vector3.Distance(transform.position, Input.mousePosition);
var dir = Input.mousePosition - HandlePivot.position;
var angle = Mathf.Atan2(-dir.y, -dir.x) * Mathf.Rad2Deg;
if (isDraging)
{
HandlePivot.rotation = Quaternion.RotateTowards(
HandlePivot.rotation,
Quaternion.Euler(0,0,Mathf.Clamp(angle, HandlePosClamp.x , HandlePosClamp.y)),
(Speed * Time.deltaTime) * distance / Weight);
} else
{
HandlePivot.rotation = Quaternion.RotateTowards(
HandlePivot.rotation,
Quaternion.Euler(0,0,0),
Speed * Time.deltaTime);
}
if (angle >= HandlePosClamp.y && isDraging)
{
Debug.Log("OPEN DOOR");
}
}
void IDragHandler.OnDrag(PointerEventData eventData)
{
}
void IPointerEnterHandler.OnPointerEnter(UnityEngine.EventSystems.PointerEventData eventData)
{
isOver = true;
}
void IPointerDownHandler.OnPointerDown(PointerEventData eventData)
{
if (isOver)
isDraging = true;
}
void IPointerUpHandler.OnPointerUp(PointerEventData eventData)
{
isDraging = false;
}
void IPointerExitHandler.OnPointerExit(UnityEngine.EventSystems.PointerEventData eventData)
{
isOver = false;
//isDraging = false;
}
}
This is exactly what I needed, works perfectly. I am very grateful, you have done an amazing job. The script is very clear and easy to understand. I really appreciate that you put a lot of effort on this.