Hi, I am trying to manually implement ricochet effect, cannot use physics for this one.
I need to calculate reflection vector of a projectile from collision point.
So far I am able to get my collision point, normal and ray are wrong.
I feel I am getting close, but the angles are wrong (reverse, actually) since my math skills appear insufficient to successfully translate online examples.
I am referring to the SO post
I’d appreciate if someone helped me to fox this.
Attached is the example project and relevant code is below.
local function onCollision(event) local obj1 = event.object1 local obj2 = event.object2 local ball local shot if (obj1.name == "ball") then ball = obj1 shot = obj2 else ball = obj2 shot = obj1 end -- this is a collision point local shotX = shot.x local shotY = shot.y - shot.height / 2 local marker = display.newRect(g, shotX, shotY, 4,4) marker:setFillColor(1,1,0) -- reference URL: https://stackoverflow.com/questions/30970103/2d-line-reflection-on-a-mirror -- get ball surface normal vector local nY = ball.x - shotX local nX = ball.y - shotY local nLength = math.sqrt(nX \* nX + nY \* nY) nX = nX / nLength nY = nY / nLength local mLine1 = display.newLine(g, shotX, shotY, ball.x, ball.y) mLine1.strokeWidth = 2 mLine1:setStrokeColor(0.5,1,0) local marker2 = display.newRect(g, ball.x + nX\*40, ball.y + nY\*40, 4,4) marker2:setFillColor(0,0,1) -- the problem is here, most likely. local rayX = (shotX - gun.x) - shotX local rayY = ( shotY - gun.y) - shotY -- local rayX = shotX - shotX -- local rayY = shotY - shotX local marker3 = display.newRect(g, rayX, rayY, 6,6) marker3:setFillColor(1,0,1) print("RayXY: "..rayX.." "..rayY) local dotProduct = (rayX \* nX) + (rayY \* nY) local dotnX = dotProduct \* nX local dotnY = dotProduct \* nY local reflRayTipX = shotX - (dotnX \* 2) local reflRayTipY = shotY - (dotnY \* 2) local mLine2 = display.newLine(g, shotX, shotY, reflRayTipX, reflRayTipY) mLine2.strokeWidth = 1 mLine2:setStrokeColor(0,1,1) -- housekeeping display.remove(shot) for i = #shots, 1, -1 do table.remove(shots, i) end end