Keeping an object within a circular radius

54 views
Skip to first unread message

Justin C.

unread,
Apr 15, 2016, 7:59:22 PM4/15/16
to HaxeFlixel
So I'm trying to do camera movement like Nuclear Throne, where you can (sorta) look around with the mouse, but the camera is ultimately snapped to your character.


I figured the best way to do this would be by using an object, and having it copy the mouse's coords and then limit itself to a radius around the player. Only problem is that I don't quite know how to do that. (I'm sure there's a way to math it out and do it, but I'm not exactly the best at math.) Any help would be fantastic, thanks! (Also, here's my code so far. It's very simplistic. cam is the object I have the camera following. Also it just limits it to a rectangle, which really isn't what I want.)

cam.setPosition(FlxG.mouse.x, FlxG.mouse.y);
var radius:Float = 96;
if (cam.x < x - radius)
cam.x = x - radius;
if (cam.x > x + radius)
cam.x = x + radius;
if (cam.y < y - radius)
cam.y = y - radius;
if (cam.y > y + radius)
cam.y = y + radius;
//Ill have to keep this type of camera movement for now




Justin C.

unread,
Apr 15, 2016, 10:02:20 PM4/15/16
to HaxeFlixel
Ah I was able to figure it out by myself, via teaching myself a little bit of trigonometry. Basically, I uses cos and sin to my advantage to get a nice circular radius going, and then making sure my cam object was within that radius.

cam.setPosition(FlxG.mouse.x, FlxG.mouse.y);
var radius:Float = 96;
var hori:Float = x + (Math.cos(FlxAngle.angleBetweenMouse(this, false))) * radius;
var verti:Float = y + (Math.sin(FlxAngle.angleBetweenMouse(this, false))) * radius;
if (((hori - x) > 0 && cam.x > hori) || ((hori - x) < 0 && cam.x < hori))
cam.x = hori;
if (((verti - y) > 0 && cam.y > verti) || ((verti - y) < 0 && cam.y < verti))
cam.y = verti;
Reply all
Reply to author
Forward
0 new messages