Shooting bullets with a joystick cocos2d - cocos2d-iphone

I have a working joystick in my cocos2d app but I cannot figure out how to make the 'player' shoot bullets out of it in the direction the joystick is pointing. I have the player moving and rotating. Also the bullets need to disappear when they hit the edges of the screen. Any help would be great. Thanks in advance.

You should get the angle from joystick.
For instance, SneakyInput has a degrees property which enables you to rotate your bullets like this :
_bullet.rotation = -joystick.degrees;
And your update method can be like this :
void update:(ccTime) delta
{
float moveAngle = _bullet.rotation;
CGPoint deltaPos = CGPointMake(cos(moveAngle) * velocity, sin(moveAngle) * velocity);
_bullet.position = ccpAdd(self.position, deltaPos);
}

Related

How do I accomplish proper trajectory with a Cocos2d-x node using Chipmunk 2D impulses and rotation?

I'm building a game with Cocos2d-x version 3.13.1 and I've decided to go with the built-in physics engine (Chipmunk 2D) to accomplish animations and collision detection. I have a simple projectile called BulletUnit that inherits from cocos2d::Node. It has a child sprite that displays artwork, and a rectangular physics body with the same dimensions as the artwork.
The BulletUnit has a method called fireAtPoint, which determines the angle between itself and the point specified, then sets the initial velocity based on the angle. On each update cycle, acceleration is applied to the projectile. This is done by applying impulses to the body based on an acceleration variable and the angle calculated in fireAtPoint. Here's the code:
bool BulletUnit::init() {
if (!Unit::init()) return false;
displaySprite_ = Sprite::createWithSpriteFrameName(frameName_);
this->addChild(displaySprite_);
auto physicsBody = PhysicsBody::createBox(displaySprite_->getContentSize());
physicsBody->setCollisionBitmask(0);
this->setPhysicsBody(physicsBody);
return true;
}
void BulletUnit::update(float dt) {
auto mass = this->getPhysicsBody()->getMass();
this->getPhysicsBody()->applyImpulse({
acceleration_ * mass * cosf(angle_),
acceleration_ * mass * sinf(angle_)
});
}
void BulletUnit::fireAtPoint(const Point &point) {
angle_ = Trig::angleBetweenPoints(this->getPosition(), point);
auto physicsBody = this->getPhysicsBody();
physicsBody->setVelocityLimit(maxSpeed_);
physicsBody->setVelocity({
startingSpeed_ * cosf(angle_),
startingSpeed_ * sinf(angle_)
});
}
This works exactly as I want it to. You can see in the image below, my bullets are accelerating as planned and traveling directly towards my mouse clicks.
But, there's one obvious flaw: the bullet is remaining flat instead of rotating to "point" towards the target. So, I adjust fireAtPoint to apply a rotation to the node. Here's the updated method:
void BulletUnit::fireAtPoint(const Point &point) {
angle_ = Trig::angleBetweenPoints(this->getPosition(), point);
// This rotates the node to make it point towards the target
this->setRotation(angle_ * -180.0f/M_PI);
auto physicsBody = this->getPhysicsBody();
physicsBody->setVelocityLimit(maxSpeed_);
physicsBody->setVelocity({
startingSpeed_ * cosf(angle_),
startingSpeed_ * sinf(angle_)
});
}
This almost works. The bullet is pointing in the right direction, but the trajectory is now way off and seems to be arcing away from the target as a result of the rotation: the more drastic the rotation, the more drastic the arcing. The following image illustrates what's happening:
So, it seems that setting the rotation is causing the physics engine to behave in a way I hadn't originally expected. I've been racking my brain on ways to correct the flight path, but so far, no luck! Any suggestions would be greatly apprecitated. Thanks!

How do I make the ball move in a certain direction?

I want to make my player, make the ball move in a certain direction, roughly 120 degrees up. At the moment the ball goes in al direction, but the ball goes up not down. The ball also goes at 4 different speeds.
if(CGRectIntersectsRect(BallA.frame, PlayerA1.frame)){
Y = arc4random() %5;
Y = 0-Y;
}
}
Ball movement
timer = [NSTimer scheduledTimerWithTimeInterval:0.006 target:self selector:#selector(BallMovement4) userInfo:nil repeats:YES];
-(void)BallMovement4{
[self Computer4Movement];
[self Collision4];
Ball4.center = CGPointMake(Ball4.center.x + X, Ball4.center.y + Y);
if (Ball4.center.x < 15) {
X = 0 - X;
}
if (Ball4.center.x > 305) {
X = 0 - X;
}
Please Help,
Thank You
Milan
It's a little unclear what you're trying to do and how your classes work, but in general, if you want to move things around, one good way to do that is to use vectors. For example, if you want the ball to move 3 pixels per frame in a given direction, the ball would have a position and a velocity vector, like this:
typedef struct Ball { // could be a class if that makes sense for your use
CGPoint position;
CGPoint velocity;
} Ball;
You'd set them to some initial value, like this:
Ball ball = { { 0.0, 0.0 }, // Ball starts at the origin
{ 1.0, 2.0 } }; // Ball starts out moving 1 pixel to the right and 2 pixels up
Then on each frame of gameplay, you'd add the velocity to the position, like this:
ball.position.x += ball.velocity.x;
ball.position.y += ball.velocity.y;
You can change the velocity, for example, when the ball hits a wall. If you're trying to simulate something real, you'd need to find the angle at which the ball hit the wall and reverse that.

Cocos2d bullet movement

As of now I have the bullet (a sprite) using a CCAction moveTo the players position. I have it set up so that the bullet always travels at a constant rate using t = d/v. But I need help so that the bullet passes through the given point and keeps going for a certain distance.
CCSprite * bullet = [CCSprite spriteWithFile:#"Projectile.png"];
int gunRange = 300;
int velocity = 300;
int t = distanceFromPlayer/velocity;
CCAction *shoot = [CCMoveTo actionWithDuration:t
position:player.position];
bullet.position = enemy.position;
if (distanceFromPlayer <= gunRange) {
[self addChild:bullet];
[bullet runAction:shoot];
}
Need to know how to shoot if in range (I think I have that part), shoot towards the player position and keep going in that direction once there (No idea on how to do this), and for the bullet sprite to be removed after it has traveled a distance equal to the gun range (No idea for this either). Please Help.
This line doesn't make sense to me:
bullet.position = enemy.position;
Use MoveTo to move the bullet to the enemy position not the above line.
Also to move the bullet past the enemy to a certain position just use the old high school trigonometry we'll all learned -- SOH CAH TOA for right triangles. You have the angle of the bullet and the distance to the enemy so using the info and right triangle trig you can have the bullet move past the target a certain distance
Hope this helps!

Can I make CCFollow follow more naturally?

I want to build a platform game with cocos2d/Box2D. I use CCFollow to follow the player sprite but CCFollow constantly puts it in the center of the screen. I want CCFollow to follow more naturally, like a human turning a camcorder with an acceptable lag, a small overshoot ...etc.
Here is a method of mine that didn't work: I attached (via a distance joint) a small physics body to the player that doesn't collide with anything, represented by a transparent sprite. I CCFollow'ed the transparent sprite. I was hoping this ghost body would act like a balloon attached to the player, hence a smooth shift in view. The problem is distance joint breaks with too heavy - too light objects. The balloon moves around randomly, and of course, it pulls the player back a little no matter how light it is.
What is a better way of following a moving sprite smoothly?
Try add this to CCActions in cocos2d libs.
-(void) step:(ccTime) dt
{
#define CLAMP(x,y,z) MIN(MAX(x,y),z)
CGPoint pos;
if(boundarySet)
{
// whole map fits inside a single screen, no need to modify the position - unless map boundaries are increased
if(boundaryFullyCovered) return;
CGPoint tempPos = ccpSub(halfScreenSize, followedNode_.position);
pos = ccp(CLAMP(tempPos.x,leftBoundary,rightBoundary), CLAMP(tempPos.y,bottomBoundary,topBoundary));
}
else {
// pos = ccpSub( halfScreenSize, followedNode_.position );
CCNode *n = (CCNode*)target_;
float s = n.scale;
pos = ccpSub( halfScreenSize, followedNode_.position );
pos.x *= s;
pos.y *= s;
}
CGPoint moveVect;
CGPoint oldPos = [target_ position];
double dist = ccpDistance(pos, oldPos);
if (dist > 1){
moveVect = ccpMult(ccpSub(pos,oldPos),0.05); //0.05 is the smooth constant.
oldPos = ccpAdd(oldPos, moveVect);
[target_ setPosition:oldPos];
}
#undef CLAMP
}
i get this from cocos2d forums.
Perhaps this http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:actions_ease can help you get an "acceleration" effect with CCFollow.

How to move a sprite at a certain angle with a joystick

Hi I have finally made a working joystick in cocos2d. I am able to rotate a sprite to the exact angle that the joystick thumb, or cap, is 'pointing'. However, I am unable to move the sprite in that same direction. Is there an easy way to move the sprite with the way I have the rotating code set up? Also is there a way to keep it moving if your thumb is still pressed, but not moving the joystick?. PS this code is all within the TouchesMoved method. PPS. the cap is the thumb, the pad is the joystick background, and the Sprite2 is the sprite that I want to move. (95, 95) is the center of the pad sprite.
if(capSprite.position.x>=padSprite.position.x){
id a3 = [CCFlipX actionWithFlipX:NO];
[sprite2 runAction:a3];
}
if(capSprite.position.x<=padSprite.position.x){
id a4 = [CCFlipX actionWithFlipX:YES];
[sprite2 runAction:a4];
}
CGPoint pos1 = ccp(95, 95);
CGPoint pos2 = ccp(capSprite.position.x, capSprite.position.y);
int offX = pos2.x-pos1.x;
int offY = pos2.y-pos1.y;
float angleRadians = atanf((float)offY/(float)offX);
float angleDegrees = CC_RADIANS_TO_DEGREES(angleRadians);
float theAngle = -1 * angleDegrees;
sprite2.rotation = theAngle;
I'm not familiar with cocos2d but I had a quick look at the documentation and this sample might be of use to you:
if keys[key.UP]:
self.target.acceleration = (200 * rotation_x, 200 * rotation_y)
I had written a long explanation answering your second question but I believe this "self.target.acceleration" solves that too. You can read more at the cocos2d API documentation.
What I generally do is get the angle, convert it to a CGPoint with ccpForAngle(float) and then multiply the CGPoint by a value:
float angle = whatever;
CGPoint anglePoint = ccpForAngle(angle);
// You will need to play with the mult value
angle = ccpMult(angle, 2.5);
// This also works with box2D or probably Chipmunk.
sprite.position = angle;