This article will show you how to collide a sprite with a rectangle.
Swingame has enough physics knowledge to determine the escape angle of a sprite if it hits a rectangle with a certain angle. To do this you only need to check if the rectangle and the sprite was in collision and if they were then you just have to call a function to make the sprite collide with the rectangle. To do this you need to follow these steps:
Declare four rectangles that encompasses the whole screen so the ball will keep bouncing off of the rectangles it hits that rectangle and will not go off the screen.
Declare four rectangle variables.
Create four rectangles (Rectangle From) from those four variables.
Create the ball sprite(Create Sprite), and set its initial position(Sprite Set X, Sprite Set Y).
Set the velocity of the sprite using vector by calling the function Sprite Set Velocity. The speed will increase with the increased numbers passed in as parameters in the Vector To function.
In the game loop draw and fill all the rectangles (Fill Rectangle) with some color
Draw (Draw Sprite) and update (Update Sprite) the sprite
Detect if there is a collision (Sprite Rect Collision) between the sprite and any of the rectangles
If there is a collision then call the funtion Collide Circle Rectangle and pass the a rectangle and the sprite as parameters. This function will collide the sprite with that particular rectangle. Do this for all four rectangles.
Refresh (Refresh Screen) the screen so all the pictures will be drawn on the game screen
Repeat the whole process until the user closes the window(Window Close Requested)
The code below shows a small program that demonstrates all these steps in making a sprite colliding with a rectangle.