Hey all,
I am trying to use polar coordinates to make a guided missile, the concept is that the code works out the vector between the rocket and its target and works out the angle difference between this and the rockets velocity vector and then tries to slowly correct for this angle.
The code seems to work best to my knowledge, but then suddenly all my vector values become NaN and I don’t know why, I have tried to check for reasons why such as a divide by 0 but no luck.
If anyone could share some light on this that would be greatly appreciated, Thanks!
I’ve posted the code for the missile logic below and have commented it all, if anyone wants to read it.
Ps I have also attached some pictures below to show the error
Rocket = class()
function Rocket:init(x,y)
-- you can accept and set parameters here
-- initial position
self.pos = vec2(x,y)
-- inital velocity
self.vel = vec2(0,1)
-- vector that links rocket position to its target
self.aim = target.pos - self.pos
self.speed = math.pow(((math.pow(self.vel.x,2))+ (math.pow(self.vel.y,2))),0.5)
-- the rockets angle, a vector pointing directly up has an angle of 0
self.angle = 0
end
function Rocket:draw()
pushMatrix()
pushStyle()
ellipse(self.pos.x + 5,self.pos.y + 15,10)
-- the translation is used so that the rotate function rotates the rectangle from the centre
translate(self.pos.x + w/2 ,self.pos.y + h/2)
rotate(-self.angle)
fill(255, 0, 229, 255)
stroke(255, 255, 255, 255)
rect(-w/2,-h/2,w,h)
popStyle()
popMatrix()
end
function Rocket:update(target)
-- update position
self.pos = self.pos + self.vel
print(self.pos)
print(self.vel)
print(self.aim)
-- update vector connecting ship and target position
self.aim = target.pos - self.pos
-- magnitude of the aim vector
self.aimMag = math.pow(((self.aim.x)*(self.aim.x)+ (self.aim.y)*(self.aim.y)),0.5)
-- angle between the ships velocity and vector between the ship to its target
self.angleRelToTarget = math.acos((self.vel.x*self.aim.x + self.vel.y*self.aim.y)/self.aimMag)
self.out = math.deg(self.angleRelToTarget)
-- print(self.angleRelToTarget)
text(self.out , self.pos.x + 50, self.pos.y + 50)
pushStyle()
strokeWidth(2)
stroke(0, 0, 0, 255)
-- this line shows the vector connecting the rocket to its target
line(self.pos.x + w/2,self.pos.y + h/2,target.pos.x,target.pos.y)
popStyle()
-- this changes the ships velocity angle
self.angle = self.angle + self.angleRelToTarget/2
-- print(math.deg(self.angle))
-- updates velocity with this new angle
self.vel = vec2(math.sin(self.angle),math.cos(self.angle))*self.speed
end