Page 1 of 1

Clamp Rotating Object

Posted: Fri Feb 03, 2012 2:18 pm
by ghostrunners
I wanted some feedback on whether using Bounding Box coordinates was the best way to clamp a rotating object to the edges/sides of a game window/area?

For example, if you had a rectangle with 10 width, and 20 height standing tall, when the object rotates 90 degrees (e.g. as its being tossed around and lands at arbitrary location), the width then becomes 20 and height becomes 10, etc. It could be any angle really. (see attached)

Here's a sample of the code I'm using to clamp a rectangular image to the left and right sides of an 800x600 window -

Code: Select all


  -- sample code run in love.update(dt)
  local p = objects.player.body
  X1, Y1, X2, Y2, X3, Y3, X4, Y4 = objects.player.shape:getBoundingBox()
  
  -- calculate distance between top left and top right points in bounding box
  dxW = X3 - X2
  dyW = Y3 - Y2
 
  -- find the distance between the two points
  heroWidth = math.sqrt(math.pow(dxW,2) + math.pow(dyW,2))
  
  -- clamp object	
  p:setX( math.min( math.max( p:getX(), heroWidth/2 ), 800 - heroWidth/2 ) )
So far it works, and since I'm just starting out [small], I wanted to make sure I'm on the right path when I tackle irregularly shaped polygons and circular images/shapes next.

Re: Clamp Rotating Object

Posted: Fri Feb 03, 2012 5:23 pm
by ivan
Are you using the physics plugin?
I'm pretty sure bounding boxes in Box2D are axis aligned.
If you are using Box2D, a simpler solution might be to put some static rectangles to border off your playarea.

In case you are handling your own collisions:

Code: Select all

heroWidth = math.sqrt(math.pow(dxW,2) + math.pow(dyW,2))
heroWidth in this case is actually the 'bounding diamater' of 'player'.
This value is actually constant (regardless of rotation) unless you change the dimensions of the shape.
So, if you have a non-rotated tall vertical 1x10 rect, heroWidth would be around 10 (sqrt(1 + 100))

Re: Clamp Rotating Object

Posted: Fri Feb 03, 2012 6:48 pm
by ghostrunners
ivan wrote:Are you using the physics plugin?
I suppose I am, because the axis stay aligned no matter what orientation the image is.

I'm unable to upload my love file, so here's the source for it - https://gist.github.com/1731469