How to rotate an object around a fixed point so it follows the mouse cursor?

I want to rotate the purple rectangle around the red square in reference to the center of the square. In addition I want to be able to have the rectangle follow the mouse cursor wherever it goes. Here is a picture for demonstration:

Here is the code I have already written:

void FixedUpdate(){
		transform.RotateAround(new Vector3(0.0f, 1.25f, -12.5f), Vector3.up, Vector3.Angle(new Vector3(1f,1f,0f),new Vector3(Input.mousePosition.x,Input.mousePosition.y, 0f)));
	}

This code doesn’t work and just rotates the rectangle around the square at a fixed pace with no noticeable influence from the mouse. Thank you for your help.

Here to be more clear. This takes place in unity3d but appears as a 2d game. Y is the direction facing the camera. I want the rectangle to only rotate around the center of the red Square(really a cube) only around the y axis(the rectangle is actually above the cube, so dont worry about them colliding). Both objects will move around with the movement keys at the same time.

1 Answer

1

Here is one solution. If the center object does not move, you can move the calculation of ‘centerScreenPos’ to Start().

using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour {    

	public Transform center;
	private Vector3 v;


	void Start() {
		// Requires the block to be directly to the right of the center
		//   with rotation set correctly on start
		v = (transform.position - center.position);
	}
	
	void Update(){
		Vector3 centerScreenPos = Camera.main.WorldToScreenPoint (center.position);
		Vector3 dir = Input.mousePosition - centerScreenPos;
		float angle = Mathf.Atan2 (dir.y, dir.x) * Mathf.Rad2Deg;
		Quaternion q = Quaternion.AngleAxis (angle, Vector3.forward);
		transform.position = center.position + q * v;
		transform.rotation = q;
	}
}

Sorry this doesn't work for me. The rectangle it seems moves around the x axis and I want to only rotate it along the y axis relative to a point. I made another comment to my original post that hopefully will clarify my intent better.

For the camera looking down the 'y' axis, change line 20 to: Quaternion q = Quaternion.AngleAxis (angle, Vector3.down);

Thank you! It seems to be almost working now. My only problem is that it is not pointing to where the mouse is exactly, there seems to be an offset. Any ideas on what I'm doing wrong?

Nevermind I got it to work. Thank you so much!

May I ask what you did to get the offset fixed? This is precisely the answer that I needed as well, and I have run into the same issue. I got my object rotating beautifully, but it does not follow the mouse. It seems to be offset by 90 degrees and reversed. EDIT: I totally got the word "beautifully" mixed up in my brain with the Pokemon Beautifly...I own it.