Adam's Lair Forum
https://forum.adamslair.net/

Rotating an object based off the mouse position
https://forum.adamslair.net/viewtopic.php?f=4&t=1158
Page 1 of 1

Author:  gregnk [ 2017/07/11, 22:23 ]
Post subject:  Rotating an object based off the mouse position

Hello,

I made this code that rotates a GameObject around a center point based off of the potion of the mouse by getting the angle difference from the mouse and the object and moving the object by that amount, making the angle difference 0. But instead of that the object just rotates around the center point endlessly.

Code:
// Get the player's location on the viewport from the camera
Camera camera = Scene.Current.FindComponent<Camera>();
Vector2 playerScreenPos = (camera != null) ? camera.GetScreenCoord(GameObj.Transform.Pos).Xy : Vector2.Zero;

// Calculate the angle that the player is looking at
// Using the pos of the mouse and the player on the screen
float playerLookAngle = (DualityApp.Mouse.Pos - playerScreenPos).Angle;
           
// Rotate the player's arm based off of the angle of the mouse
weaponObj.Transform.TurnToAbs(playerLookAngle - 1.5f);

Vector2 mouseSpacePos = camera.GetSpaceCoord(DualityApp.Mouse.Pos).Xy;
Vector3 weaponPos = weaponObj.Transform.Pos;
float angleFromMouse = (weaponPos.Xy - mouseSpacePos).Angle;

MathF.TransformCoord(ref weaponPos.X, ref weaponPos.Y, angleFromMouse, 1, GameObj.Transform.Pos.X, GameObj.Transform.Pos.Y);

weaponObj.Transform.MoveToAbs(weaponPos);

Author:  Adam [ 2017/07/12, 21:43 ]
Post subject:  Re: Rotating an object based off the mouse position

I don't see an obvious error on what I think are the relevant lines (the first few determine the rotation and apply it, right?), but it's a bit hard to say what's going on without more context. Can you isolate the problem and pin it down to something that is less dependent on project specifics?

Edit: If you're unsure how to further debug this, maybe add a VisualLog text on screen to output realtime info on values? Alternatively, do the same with a regular log and observe how the values change while you're moving the mouse cursor. Live info can help a lot in these cases!

Author:  gregnk [ 2017/07/12, 23:12 ]
Post subject:  Re: Rotating an object based off the mouse position

I fixed it. The issue was with how angleFromMouse was calculated. angleFromMouse was calculating what direction the mouse was facing rather than the difference between mouseSpacePos and weaponPos.

So The right code would be:
Code:
float angleFromMouse = (mouseSpacePos - GameObj.Transform.Pos.Xy).Angle - (weaponPos.Xy - GameObj.Transform.Pos.Xy).Angle


Also I was able to check the values in realtime by declaring them in the global scope and enabling debug mode in the object inspector. It was really helpful! :+1:

Page 1 of 1 All times are UTC + 1 hour [ DST ]
Powered by phpBB® Forum Software © phpBB Group
http://www.phpbb.com/