program HowToCollideTwoSprites; uses SwinGame,sgTypes; procedure Main(); var earth : Sprite; asteroid : Sprite; begin OpenGraphicsWindow('Colliding Sprites' ,800 ,600 ); ClearScreen(ColorWhite ); LoadBitmapNamed('earth' ,'earth.png' ); LoadBitmapNamed('asteroid' ,'asteroid.png' ); earth := CreateSprite(BitmapNamed('earth' ) ); SpriteSetX(earth ,700 ); SpriteSetY(earth ,100 ); SpriteSetVelocity(earth ,VectorTo(-0.8 ,0.6 ) ); asteroid := CreateSprite(BitmapNamed('asteroid' ) ); SpriteSetX(asteroid ,100 ); SpriteSetY(asteroid ,500 ); SpriteSetVelocity(asteroid ,VectorTo(1 ,-0.6 ) ); repeat ProcessEvents(); ClearScreen(ColorWhite ); DrawSprite(earth ); UpdateSprite(earth ); DrawSprite(asteroid ); UpdateSprite(asteroid ); if SpriteCollision(earth ,asteroid ) then CollideCircles(asteroid ,earth ); RefreshScreen(); until WindowCloseRequested(); FreeSprite(earth ); FreeSprite(asteroid ); ReleaseAllResources(); end; begin Main(); end.
How To Collide Two Sprites
This article will show you how to collide two sprites with each other.
SwinGame has enough physics knowledge to determine the escape angle of a circular sprite if it hits another sprite at a certain angle. To do this you only need to check if the sprites are in collision, and if they are then you just call a function to collide them with each other. To be able to do it, you just need to follow these steps:
- Create two sprites (Create Sprite) Set their initial position (Sprite Set X) and velocity (Sprite Set Velocity). When giving the velocity of the sprites, make sure that they will collide with each other before going off the screen.
- In the game loop check if the sprites are in collision (Sprite Collision), if they are then call the function Collide Circles and pass both sprites as parameters. This function will help you to collide the sprites with each other.
The code below shows a small program that demonstrates all these steps for colliding two sprites with each other.
If there is a useful hint you will find it in a box like this
Suggested projects will appear here.