[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]
Re: [pygame] Limited Range?
A quick test with the timeit module suggest that the ** operator is not
slower.
x*x and x**2 are exactly the same speed.
However, you are correct that x**0.5 is a slow operation.
raising something to the power of 0.5 is the same as taking its square
root
x**0.5 is the same as math.sqrt(x)
Here is how I would write the distance check:
def is_in_range(enemy, tower):
return (enemy.x-tower.x)**2 + (enemy.y-tower.y)**2 <= tower.range**2
---
James Paige
On Tue, Nov 03, 2009 at 09:24:50PM -0500, Michael George wrote:
> If you find this is too slow, you'll get much better performance by
> removing the **'s, they're quite slow compared to other arithmetic. Use
> x*x instead of x**2 and square both sides of the inequality to remove
> the **0.5.
>
> P.F.C. wrote:
> >I'm not getting the attachment but this might help.
> >
> >If your doing range as a circle with radius = r then:
> >
> >if ((enemy.x-tower.x)**2+ (enemy.y-tower.y)**2)**0.5<=r: attack!!!
> >
> >basically, you'd be using Pythagorean theorem to find the distance to
> >check if it attacks or not.
> >
> >Checking distances for every tower and every unit could become a
> >bottle neck but would work.
> >
> >If you have performance problems you could also incorporate a grid.
> >When every unit moves it can do a check to see in what section of the
> >map it is found in (ie, grid could have 10x10 tiles in each square)
> >and you would only check the distance of creeps in the grids that are
> >in range of the tower.
> >
> >One thing to keep in mind would be that in some cases you may be able
> >to stop the iteration as soon as you find someone who is attackable
> >(if the tower attacks random creeps) otherwise you just compare the
> >distances of the creeps and sort.
> >
> >You may want to google for circle collision detection
> >
> >
> >-- Maranatha!
> >---------------------------------
> >PFC aka Fezzik aka GAB
> >
> >
> >On Tue, Nov 3, 2009 at 8:27 PM, Yanom Mobis <yanom@xxxxxxxxxxxxxx
> ><mailto:yanom@xxxxxxxxxxxxxx>> wrote:
> >
> > so, I wrote this tower defense game (zip archive attached) and I
> > was wondering how I should go about implementing limited range
> > (each tower can only shoot so far) in the code.
> >
> >
> >
>
>