-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTut21.cpp
86 lines (71 loc) · 2.33 KB
/
Tut21.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// C++ Sfml Made Easy Tutorial 21 - Sound
// CodingMadeEasy
#include<SFML/Audio.hpp>
#include<SFML/Graphics.hpp>
#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<ctime>
#include<cmath>
const int PLAYERWIDTH = 10;
const int PLAYERHEIGHT = 10;
const int OBJECTWIDTH = 10;
const int OBJECTHEIGHT = 10;
const float MOVESPEED = 0.2f;
#define ScreenWidth 800
#define ScreenHeight 600
void Collision(sf::RenderWindow &Window, sf::Sound &collision, sf::Shape player, sf::Shape &object)
{
if(player.GetPosition().x + PLAYERWIDTH < object.GetPosition().x ||
player.GetPosition().x > object.GetPosition().x + OBJECTWIDTH ||
player.GetPosition().y + PLAYERHEIGHT < object.GetPosition().y ||
player.GetPosition().y > object.GetPosition().y + OBJECTHEIGHT)
{
// No Collision
}
else
{
collision.Play();
object.SetPosition(rand() % (ScreenWidth - OBJECTWIDTH), rand() % (ScreenHeight - OBJECTHEIGHT));
}
}
void Controls(sf::RenderWindow &Window, sf::Shape &player)
{
if(Window.GetInput().IsKeyDown(sf::Key::Right))
player.Move(MOVESPEED, 0);
else if(Window.GetInput().IsKeyDown(sf::Key::Left))
player.Move(-MOVESPEED, 0);
else if(Window.GetInput().IsKeyDown(sf::Key::Down))
player.Move(0, MOVESPEED);
else if(Window.GetInput().IsKeyDown(sf::Key::Up))
player.Move(0, -MOVESPEED);
}
int main()
{
sf::Shape player = sf::Shape::Rectangle(0, 0, PLAYERWIDTH, PLAYERHEIGHT, sf::Color::Red);
sf::Shape object = sf::Shape::Rectangle(0, 0, OBJECTWIDTH, OBJECTHEIGHT, sf::Color::Blue);
player.SetPosition(0, 0);
object.SetPosition(100, 100);
sf::RenderWindow Window(sf::VideoMode(ScreenWidth, ScreenHeight, 32), "SFML - CodingMadeEasy");
sf::SoundBuffer buffer;
sf::Sound collision;
if(buffer.LoadFromFile("collision.wav"))
collision.SetBuffer(buffer);
srand(time(0));
while(Window.IsOpened())
{
sf::Event Event;
while(Window.GetEvent(Event))
{
if(Event.Type == sf::Event::Closed || Event.Key.Code == sf::Key::Escape)
Window.Close();
}
Controls(Window, player);
Collision(Window, collision, player, object);
Window.Clear();
Window.Draw(object);
Window.Draw(player);
Window.Display();
}
return 0;
}