This sample code shows how to shoot projectiles aimed at a location.
It also shows how to make an enemy react to being hit.
Use direction keys to walk around
Press (X) to shoot
press (C) to launch a grenade ;)
edit: err actually,
press (C) to shoot
press (X) to launch a grenade
Krystman, are you using a playstation controller (O & X reversed) ? ;)
Nice. Love the kick back on the alien. The grenade is awesome too, gonna have to borrow that code.
Here's the function I've been using forever to get the dx,dy for an object.
function dir_calc(ax,ay, bx,by, speed) local angle=atan2(ay-by, ax-bx) local dx=cos(angle)*speed local dy=sin(angle)*speed return dx,dy end
funny that you'd both go through trigonometry for this,
I find it more straightforward to normalize the dir vector:
function shoot(ox,oy, tx,ty, speed) local dx,dy=tx-ox,ty-oy local d=speed/sqrt(dx*dx+dy*dy) return dx*d,dy*d end
I think it should execute somewhat faster too.
on the other hand once you have the angle and/or its cos&sin you could use them to rotate a turret for instance.
I got kind of used to angles being in 0..1 but I still think degrees are more intuitive. the one thing I can't get used to is sin() being inverted. I usually end up putting minuses here or there until it looks good. that's a real PITA. on bigger projects I redefine those functions as they should be, but that's unfunny. also there's no tan().
buttons 4/5 (aka o/x) default on z/x on a keyboard (have a look in keyconfig),
A/B on an xbox controller and... X/O on a ps controller.
but well, you don't even need a ps controller to get confused about that...
@ultrabrite Yes, I usually avoid trigonometry myself if I can. It can be very useful tho. For example, you can spread out projectiles or make enemies miss on purpose. I posted the code for those cases where winging it doesn't cut it anymore and you REALLY need that specific formula. ;D
Learning the angles and trig stuff was a hurdle for me. I had no prior experience with such math so it was uphill but once I had some functions to use, I understood things better. Anything with rotation, the trig is necessary (I assume) and I haven't seen any noticeable problems in performance...but I doubt I'm pushing things much with what I make.
I just was reading about normalizing vectors yesterday and the dot product between two vectors. I can't speak for anyone but myself, but I really love reading about how maths can explain/'draw'/represent the world. I knew going in I'd have to become more comfortable with using maths. I didn't know how much I'd love it though. Sometimes I find myself just reading math stuff on the web for the fun of it.. I wouldn't have guessed that about myself a few years back in a million years.
Degrees, radians, 0 to 1. It's all Pi to me. And coffee.
[Please log in to post a comment]