0

Let's say i have an object which I have to destroy by shooting (projectile motion). The position of the object is random (as for now, just integers, to make it easier). Even when my 'bullet' looks to be just in place, the loop doesn't break. Probably the program doesn't consider graph 1 and graph 2 as equal at any point. I tried few things about that if condition but it nothing worked. Can anyone tell me what I must add/change?

import matplotlib.pylab as plt
import numpy as np 
import random
g = 10
c = []
d = []
fig = plt.figure()
L = random.randint(5.0,18.0)
while True:
    try:
    #velocity
        v = float(input("What is the velocity?\n>"))
    #angle
        a = np.radians(float(input("What is the angle?\n>")))
        z = np.sin(2*a)*v**2/g #max range
        h = ((v**2*(np.sin(a))**2)/(2*g)) #max. height
        x= np.linspace(0, z, 1000)
        #y values
        y = (x*np.tan(a) - (g*x**2)/(2*v**2*((np.cos(a))**2)))
        ax = plt.axes(xlim=(0, 1.5*L), ylim=(0, 1.2*h))

        plt.ion() #interactive graph
        #previous tries
        plt.plot(c,d, '.', color = 'lightgrey')
        plt.pause(0.01)
        #enemy object
        graph1 = plt.plot(L, 0, 'o', color = 'r', markersize=30)
        plt.pause(0.01)
        #actual shoot
        graph2 = plt.plot(x,y, '.', color = 'b', ms = 7)
        plt.pause(0.01)

        if np.any(graph2) == np.any(graph1):
            print("You have destroyed the enemy object!")
            plt.show()
            break
        else:
            print("You've missed. Keep shooting!")
            c.append(x)
            d.append(y)
            plt.show()
            continue
    except ValueError:
        print("Sorry, I can't understand.")
Tokela
  • 17
  • 1

1 Answers1

0

You don't need to plot at all to find the intersection. In fact, I don't think matplotlib can help here. The returned value of plt.plot is a list containing a single Line2D object - you could get back your original x and y values by doing

x_new = graph1[0].get_xdata()
y_new = graph1[0].get_ydata()

However, you'd only do that if your code was for some reason analyzing plots generated by a completely different function and wasn't allowed to have the original data. In your case, just use your x and y directly and find the intersection. It looks like you might be trying to do

if np.any((y == 0) * (x == L)):
    print "You have destroyed the enemy object!"

Which should check if any point (x,y) is located at (0,L). The * acts as an element-by-element 'and' operator for boolean arrays. Here are some more comprehensive answers about finding intersections of two arrays.

If you're trying to build a game, look at pygame. It has all kinds of methods to detect collisions much more easily than in numpy.

Community
  • 1
  • 1
Ben Schmidt
  • 401
  • 2
  • 8