program HowToCollideSpriteWithLines; uses SwinGame,sgTypes; procedure Main(); var leftLine : LineSegment; ball : Sprite; topLine : LineSegment; bottomLine : LineSegment; rightLine : LineSegment; begin OpenGraphicsWindow('Bouncing Ball' ,800 ,600 ); ClearScreen(ColorWhite ); LoadBitmapNamed('ball' ,'ball_small.png' ); leftLine := LineFrom(10 ,10 ,10 ,590 ); rightLine := LineFrom(790 ,10 ,790 ,590 ); topLine := LineFrom(10 ,10 ,790 ,10 ); bottomLine := LineFrom(10 ,590 ,790 ,590 ); ball := CreateSprite(BitmapNamed('ball' ) ); SpriteSetX(ball ,100 ); SpriteSetY(ball ,500 ); SpriteSetVelocity(ball ,VectorTo(1 ,-0.6 ) ); repeat ProcessEvents(); ClearScreen(ColorWhite ); DrawLine(ColorRed ,leftLine ); DrawLine(ColorRed ,rightLine ); DrawLine(ColorRed ,topLine ); DrawLine(ColorRed ,bottomLine ); DrawSprite(ball ); UpdateSprite(ball ); if CircleLineCollision(ball ,leftLine ) then CollideCircleLine(ball ,leftLine ); if CircleLineCollision(ball ,rightLine ) then CollideCircleLine(ball ,rightLine ); if CircleLineCollision(ball ,topLine ) then CollideCircleLine(ball ,topLine ); if CircleLineCollision(ball ,bottomLine ) then CollideCircleLine(ball ,bottomLine ); RefreshScreen(); until WindowCloseRequested(); FreeSprite(ball ); ReleaseAllResources(); end; begin Main(); end.
How To Collide Sprite With Lines
This article will show you how to collide a sprite with a line.
Swingame has enough physics knowledge to determine the escape angle of a sprite if it hits a line with a certain angle. To do this you only need to check if the line 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 line. To do this you need to follow these steps:
- Declare four lines that encompasses the whole screen so the ball will keep bouncing off of the lines it hits and will not go off the screen.
- Declare four lineSegment variables.
- Create four lines (Line 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 all the lines
- Draw (Draw Sprite) and update (Update Sprite) the sprite
- Detect if there is a collision (Circle Line Collision) between the sprite and the line
- If there is a collision then call the funtion Collide Circle Line and pass the line and the sprite as parameters. This function will collide the line with the sprite
- 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 line.
If there is a useful hint you will find it in a box like this
Suggested projects will appear here.