0
\$\begingroup\$

I am working on a game where one spaceship("Origin") can shoot a dumb projectile("Projectile") at another spaceship("Target").

Since the target is moving we will have to lead the target. The projectile will move at a given speed (to be clear I differentiate between "velocity" which i use when talking about a vector and "speed" when i am talking about the length of said vector).

I am trying to calculate the point where I will have to aim in order to hit the target (assuming it does not change its velocity).

I tried this example.

UPDATED THE CODE

This is part of the "projectile" class that a wrote. self.targetVessel is the target self.originVessel is the shooter this function is called one in the constructor so that self.originVessel.velocity is the starting velocity self.totalSpeed is the "kick" that the projectile gets from the shooter

    def takeAim (self):
    t = 0

    #self.totalSpeed += math.sqrt(np.dot(self.originVessel.velocity, self.originVessel.velocity))

    posRel = self.pos - self.targetVessel.pos 
    velRel = self.originVessel.velocity - self.targetVessel.velocity
    #velRel =  - self.targetVessel.velocity #this hits the target but the speeds don't add up

    a = (np.dot(velRel, velRel))-(self.totalSpeed**2)
    b = 2.0 * (np.dot(velRel,posRel))
    c = np.dot(posRel, posRel)

    disc = (b*b) - (4.0*a*c)

    print("Disc: ", disc)

    if disc < 0:
        print("Target is too fast - no point shooting!")
    else:
        t0 = (-b - math.sqrt(disc)) / (2.0*a)
        t1 = (-b + math.sqrt(disc)) / (2.0*a)

        print("t0: ", t0)
        print("t1: ", t1)

        if t0 < 0:
            t = t1
            print ("Choosing t1")
        elif t1 < 0:
            t = t0
            print ("Choosing t0")
        else:
            if t0 < t1:
                t = t0
                print("Choosing t0")
            else: 
                t = t1
                print("Choosing t1")

    shoot = velRel + (posRel / t)
    self.velocity =  shoot + self.targetVessel.velocity
    self.aimPoint = self.targetVessel.pos + self.targetVessel.velocity*t
    targetDirection = self.aimPoint-self.pos
    targetDirection = targetDirection / math.sqrt(np.dot(targetDirection,targetDirection))
    self.velocity = (targetDirection * self.totalSpeed)
\$\endgroup\$
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.