/
Ball.cs
64 lines (56 loc) · 1.81 KB
/
Ball.cs
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
using System;
using BallBounceMVC.Models;
using Microsoft.Xna.Framework;
namespace BallBounceMVC.Entities
{
public class Ball : GameObject
{
public int Width { get; set; }
public int Height { get; set; }
public Ball(int width, int height, Vector2 startPosition, Vector2 startDirection)
{
Width = width;
Height = height;
Position = startPosition;
Velocity = startDirection;
}
public void HandleCollisionWithAnyGameObject(World world)
{
var ballRectangle = new Rectangle((int)Position.X, (int)Position.Y, Width, Height);
var frame = world.GetFrameModel();
if (frame.IntersectsWithTopWall(ballRectangle))
{
ChangeVelocityToDown();
}
if (frame.IntersectsWithLeftWall(ballRectangle))
{
ChangeVelocityToRight();
}
if (frame.IntersectsWithRightWall(ballRectangle))
{
ChangeVelocityToLeft();
}
var player = world.GetPlayerModel();
if (player.IntersectsWith(ballRectangle))
{
if (Math.Sign(Velocity.Y) >= 0)
Velocity.Y = -(Velocity.Y);
}
}
private void ChangeVelocityToLeft()
{
if (Math.Sign(Velocity.X) >= 0)
Velocity.X = -(Velocity.X);
}
private void ChangeVelocityToRight()
{
if (Math.Sign(Velocity.X) <= 0)
Velocity.X = -(Velocity.X);
}
private void ChangeVelocityToDown()
{
if (Math.Sign(Velocity.Y) <= 0)
Velocity.Y = -(Velocity.Y);
}
}
}