Home > Blockchain >  How do I set the rotation of one object to the angle between another object and the mouse position?
How do I set the rotation of one object to the angle between another object and the mouse position?

Time:01-28

I'm making a 2D shooter game where the player's arm should be able to pivot based on your mouse position. I have a "joint" object set to the shoulder of the arm for it to rotate around. Everything I've searched pointed me to transform.RotateAround, so I used that, but the problem is the arm doesn't FACE the mouse, it just continuously rotates based on the angle of the mouse. I know of transform.rotation, but I don't believe you can rotate around a point like that. Here's what I currently have:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RotateArm : MonoBehaviour
{
    public GameObject joint;
    public Camera cam;

    private Vector3 mousePosition;
    private Vector3 lookAtPosition;

    void Update()
    {
        mousePosition = Input.mousePosition;
        lookAtPosition = cam.ScreenToWorldPoint(mousePosition);

        var angle = Vector2.Angle(lookAtPosition, joint.transform.position);
        transform.RotateAround(joint.transform.position, Vector3.forward, angle);
    }
}

CodePudding user response:

Calculate the angle between the arm's current forward direction and the direction towards the mouse, then use that angle to set the arm's rotation.

void Update()
{
    mousePosition = Input.mousePosition;
    lookAtPosition = cam.ScreenToWorldPoint(mousePosition);

    Vector3 direction = lookAtPosition - joint.transform.position;
    float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
    Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward);
    transform.rotation = rotation;
}

CodePudding user response:

I found the solution to my problem. All I had to do was add the arm as a child object of the joint. I attached my rotate script to the joint, and made the joint rotate toward the mouse. This made the arm rotate perfectly around the joint.

  • Related