summaryrefslogtreecommitdiffstats
path: root/src/Collision.hs
blob: 30ec6e9c195fa70e39383a5dd2e5d5732e86586a (plain)
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
module Collision ( collisionTankBorder
                 , collisionBulletBullet
                 , collisionBulletTank
                 ) where

import Tank
import Game

import Data.Fixed
import Data.Ratio

tankWidth :: Micro
tankWidth = 0.95

tankLength :: Micro
tankLength = 0.95

bulletDiameter :: Micro
bulletDiameter = 0.05

collisionTankBorder :: Micro -> Micro -> Tank -> Tank
collisionTankBorder lw lh tank = tank {tankX = newx, tankY = newy}
    where
      dir = (fromRational . toRational . tankDir $ tank)*pi/180
      cosd = fromRational (round ((cos dir)*1000000)%1000000)
      sind = fromRational (round ((sin dir)*1000000)%1000000)
      
      points = [ (tankLength/2, tankWidth/2)
               , (-tankLength/2, tankWidth/2)
               , (-tankLength/2, -tankWidth/2)
               , (tankLength/2, -tankWidth/2)
               ]
      
      rotp (x, y) = (cosd*x - sind*y, sind*x + cosd*y)
      transp (x, y) = (x + tankX tank, y + tankY tank)
      
      pointst = map (transp . rotp) points
      minx = minimum $ map fst pointst
      maxx = maximum $ map fst pointst
      miny = minimum $ map snd pointst
      maxy = maximum $ map snd pointst
      
      dx = if minx < 0 then (-minx) else if maxx > lw then (-maxx+lw) else 0
      dy = if miny < 0 then (-miny) else if maxy > lh then (-maxy+lh) else 0
      
      newx = (tankX tank) + dx
      newy = (tankY tank) + dy

collisionBulletBullet :: (Bullet, Bullet) -> (Bullet, Bullet) -> Bool
collisionBulletBullet (b1, b1') (b2, b2') = distancesq < (bulletDiameter^2)
    where
      distancesq = (bulletX b1' - bulletX b2')^2 + (bulletY b1' - bulletY b2')^2

collisionBulletTank :: (Bullet, Bullet) -> (Tank, Tank) -> Bool
collisionBulletTank (b, b') (tank, tank') = (not ((between bx minx maxx) && (between by miny maxy))) && ((between bx' minx maxx) && (between by' miny maxy))
    where
      between x a b = x >= a && x <= b
      
      dir t = (fromRational . toRational . tankDir $ t)*pi/180
      cosd t = fromRational (round ((cos $ dir t)*1000000)%1000000)
      sind t = fromRational (round ((sin $ dir t)*1000000)%1000000)
      
      rotp t (x, y) = ((cosd t)*x + (sind t)*y, -(sind t)*x + (cosd t)*y)
      transp t (x, y) = (x - tankX t, y - tankY t)
      
      (bx, by) = (rotp tank) . (transp tank) $ (bulletX b, bulletY b)
      (bx', by') = (rotp tank') . (transp tank') $ (bulletX b', bulletY b')
      
      minx = -tankLength/2
      maxx = tankLength/2
      miny = -tankWidth/2
      maxy = tankWidth/2