@name tr_test_game4
@inputs 
@outputs 
@persist Lines:table [PlayerPos PlayerDir]:vector [PlayerSpeed PlayerYaw]
@persist [CurrentLineStart CurrentLineFinish]:vector Debug
@trigger none




if (first()) {
    
    Debug = 1000
    
    
    holoCreate(1)
    holoAlpha(1, 100)

    PlayerPos   = entity():pos()
    PlayerDir   = vec(1, 0, 0)    
    PlayerSpeed = 10
    PlayerYaw   = 0

    CurrentLineStart = CurrentLineFinish = PlayerPos
    
    
    function number lDir(PointA:vector, PointB:vector, PointC:vector) {
        return sign((PointB[1] - PointA[1])*(PointC[2] - PointA[2]) - (PointC[1] - PointA[1])*(PointB[2] - PointA[2]))
    }
    
    function number lineSegmentIntersection([LineAP1 LineAP2]:vector, [LineBP1 LineBP2]:vector) {
        return lDir(LineAP1, LineAP2, LineBP1) != lDir(LineAP1, LineAP2, LineBP2) & lDir(LineBP1, LineBP2, LineAP1) != lDir(LineBP1, LineBP2, LineAP2)
    }
    
}


interval(90)

local Rotate = owner():keyPressed("up") - owner():keyPressed("down")
if (changed(Rotate)) {
    PlayerYaw += sign(Rotate)
}

if (changed(PlayerYaw) & !first()) {
    CurrentLineStart  = CurrentLineFinish  #set start to old finish
    CurrentLineFinish = PlayerPos          #set finish to current pos
    
    Debug++
    holoCreate(Debug, CurrentLineStart, vec(1/3))
    holoColor(Debug, vec4(255, 255, 0, 100))

    Debug++
    holoCreate(Debug, CurrentLineFinish, vec(1/6))
    holoColor(Debug, vec4(0, 255, 0, 100))
    
    Lines:pushArray( array(CurrentLineStart, CurrentLineFinish) )

}

local Check = 0

local NextPlayerPos = PlayerPos + PlayerDir*PlayerSpeed
for (I = 1, Lines:count()) {
    local CheckStart = Lines[I, array][1, vector]
    local CheckFinish = Lines[I, array][2, vector]

    if (lineSegmentIntersection(CheckStart, CheckFinish, PlayerPos, NextPlayerPos)) {
        Check++
        break
    }
}

if (Check) {
    print("Hit")
}
else {
    PlayerDir = vec(1, 0, 0):rotate(0, PlayerYaw*90, 0)
    PlayerPos = PlayerPos + PlayerDir*PlayerSpeed
}

holoPos(1, PlayerPos)
