on how to shoot an object to the location of your touch using cocos2d.
Unfortunatley, i'm not using cocos for my current project, and am really having trouble being able to shoot an object to the location of my touch.
I've written the code to create the bullet, load it into an array, and move it along it's path. Unfortunatley, i am unable to shoot it towards the direction of my touch.
Can someone help me be able to devise a method to do so, without using cocos2d?
Post the code that moves the bullet along the path. The general idea is to:
(1) get the direction from the object to the touch. This will generally be in the form of a slope, like dx/distance and dy/distance.
(2) figure out how far the bullet will move this frame; you'll need the slope above, the time elapsed, and the speed of the bullet. Something like this:
Once you get it working you can decide how to optimize - for example (directionx * speed) never changes over the life of the bullet, so you could calculate that once and store it as speedx and speedy instead.
Firstly you need somewhere to store the direction or speed of each bullet. You could subclass UIImageView to create a Bullet class*, give it directionx and directiony properties, and then do something like this. You'll have to pass in the location of the touch:
Note I changed your variable name to "myBullet" and named the class "Bullet." Classes usually start with an uppercase, and variables with a lowercase. Now you can move each bullet in the right direction:
*subclassing UIImageView is bad long-term practice, but probably fine for your first few games. Eventually you'll want to separate the model from the view.
Sorry, that was a typo. Should have been myBullet.
Dictated but not compiled,
Smasher
Pardon my ignorance,
But i am honestly having serious trouble implementing this function. I feel i may have tried to implement this the wrong way.
I'm looking to do something like this: (..I just can't for the life of my get it to run)
1: Fire the bullet from the position of my character.center ,
Code:
// if the cannonball is on the screen
if (bulletOnScreen)
{
// update cannonball position
bullet.x += TIME_INTERVAL * bulletlVelocity.x;
bullet.y += TIME_INTERVAL * bulletVelocity.y;
..Then destroy the bullet if it goes off screen, so i can create another one.
I'm stuck.
However, i really appreciate your time and effort so far, Smasher.
Did you create a "Bullet" class that inherits from UIImageView like I suggested? That would allow you to give each bullet a different velocity variable. Then you should be able to write a nice little "moveBullet" method for the Bullet class:
You can't have a single variable bulletVelocity, since each bullet has its own velocity. Now you can just call [myBullet moveBullet] to move the bullet.
If you want to store velocity instead of direction then createBullet is pretty much the same except for the last two lines: