Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

I am trying to test for a collision from a rectangle to a circle and I need to calculate the closest point on a rectangle to a point any ideas?

 

Public Shared Function HasCollisionOccured(ByVal Object1Pos As Vector2, ByVal Object2Pos As Vector2, ByVal Object1Radius As Single, ByVal Object2Size As Size) As Boolean
           HasCollisionOccured = False

           Dim Gap, distance, difX, DifY As Single
           difX = Object1Pos.X - Object2Pos.X
           DifY = Object1Pos.Y - Object2Pos.Y

           Dim angle As Single = Math.Atan2(Object2Pos.X - Object1Pos.X, Object2Pos.Y - Object1Pos.Y)

MISSING CODE



           Dim Object2Radius As Single

           Dim x, y As Single
           x = Math.Tan(angle) * Object2Size.Height

           If x > Object2Size.Width Then
               x = Object2Size.Width
               y = Math.Tan(angle) * Object2Size.Width
           End If

           If x < -Object2Size.Width Then
               x = -Object2Size.Width
               y = Math.Tan(angle) * Object2Size.Width
           End If

           distance = Math.Sqrt(difX * difX + DifY * DifY)
           Gap = distance - (Object1Radius + Object2Radius)

           If Gap < 0 Then
               Return True
           End If

       End Function

  • Leaders
Posted

How about checking the distance that each corner is from the center of the circle?

 

Another method may be to compare the center of the rectangle to the center of the circle.

X = R.X - C.X

Y = R.Y - C.Y

If X and Y are positive, use the top left corner.

If X and Y are negative, use the bottom right corner.

If X is negative and Y positive, use the top right corner and

if X is positive and Y negative, use the bottom left corner. :)

Iceplug, USN

One of my coworkers thinks that I believe that drawing bullets is the most efficient way of drawing bullets. Whatever!!! :-(

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...