move from one scene to another in cocos 2D_android - android

I want to make a game with levels. That means in the first level the user have to kill some targets; if he wins he passes to the next level with new targets and new background.
I use this game tutorial.
I have these classes
---->
package game.wael.ialhi;
import org.cocos2d.layers.CCScene;
import org.cocos2d.nodes.CCDirector;
import org.cocos2d.opengl.CCGLSurfaceView;
import org.cocos2d.sound.SoundEngine;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
public class SimpleGame extends Activity{
protected CCGLSurfaceView _glSurfaceView;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
_glSurfaceView = new CCGLSurfaceView(this);
setContentView(_glSurfaceView);
}
#Override
public void onStart()
{
super.onStart();
CCDirector.sharedDirector().attachInView(_glSurfaceView);
CCDirector.sharedDirector().setDeviceOrientation(CCDirector
.kCCDeviceOrientationLandscapeLeft);
CCDirector.sharedDirector().setDisplayFPS(true);
CCDirector.sharedDirector().setAnimationInterval(1.0f / 60.0f);
CCScene scene = GameLayer.scene();
CCDirector.sharedDirector().runWithScene(scene);
}
#Override
public void onPause()
{
super.onPause();
CCDirector.sharedDirector().pause();
SoundEngine.sharedEngine().stopSound();
}
#Override
public void onResume()
{
super.onResume();
CCDirector.sharedDirector().resume();
}
#Override
public void onStop()
{
super.onStop();
CCDirector.sharedDirector().end();
SoundEngine.sharedEngine().stopSound();
}
}
I made some modification in this GameLayer class. In the update method I added these lines so that when the user wins he pass to the next scene (GameLayer1)
---->
CCScene scene=GameLayer1.scene();
CCDirector.sharedDirector().runWithScene(scene);
and this the complete class
------>
package game.wael.ialhi;
public class GameLayer extends CCColorLayer{
protected ArrayList<CCSprite> _targets;
protected ArrayList<CCSprite> _projectiles;
protected int _projectilesDestroyed;
public static int nb;
public static CCScene scene()
{
CCScene scene = CCScene.node();
CCColorLayer layer = new GameLayer(ccColor4B.ccc4(255, 255, 255, 255));
scene.addChild(layer);
return scene;
}
protected GameLayer(ccColor4B color)
{
super(color);
this.setIsTouchEnabled(true);
_targets = new ArrayList<CCSprite>();
_projectiles = new ArrayList<CCSprite>();
_projectilesDestroyed = 0;
CGSize winSize = CCDirector.sharedDirector().displaySize();
CCSprite player = CCSprite.sprite("Player.png");
player.setPosition(CGPoint.ccp(player.getContentSize().width / 2.0f,
winSize.height / 2.0f));
addChild(player);
// Handle sound
Context context = CCDirector.sharedDirector().getActivity();
SoundEngine.sharedEngine().preloadEffect(context, R.raw.pew_pew_lei);
SoundEngine.sharedEngine().playSound(context, R.raw.background_music_aac,
true);
this.schedule("gameLogic", 1.0f);
this.schedule("update");
}
#Override
public boolean ccTouchesEnded(MotionEvent event)
{
// Choose one of the touches to work with
CGPoint location =
CCDirector.sharedDirector().convertToGL(CGPoint.ccp(event.getX(),
event.getY()));
// Set up initial location of projectile
CGSize winSize = CCDirector.sharedDirector().displaySize();
CCSprite projectile = CCSprite.sprite("Projectile.png");
projectile.setPosition(20, winSize.height / 2.0f);
// Determine offset of location to projectile
int offX = (int)(location.x - projectile.getPosition().x);
int offY = (int)(location.y - projectile.getPosition().y);
// Bail out if we are shooting down or backwards
if (offX <= 0)
return true;
// Ok to add now - we've double checked position
addChild(projectile);
projectile.setTag(2);
_projectiles.add(projectile);
// Determine where we wish to shoot the projectile to
int realX = (int)(winSize.width + (projectile.getContentSize().width /
2.0f));
float ratio = (float)offY / (float)offX;
int realY = (int)((realX * ratio) + projectile.getPosition().y);
CGPoint realDest = CGPoint.ccp(realX, realY);
// Determine the length of how far we're shooting
int offRealX = (int)(realX - projectile.getPosition().x);
int offRealY = (int)(realY - projectile.getPosition().y);
float length = (float)Math.sqrt((offRealX * offRealX) + (offRealY *
offRealY));
float velocity = 480.0f / 1.0f; // 480 pixels / 1 sec
float realMoveDuration = length / velocity;
// Move projectile to actual endpoint
projectile.runAction(CCSequence.actions(
CCMoveTo.action(realMoveDuration, realDest),
CCCallFuncN.action(this, "spriteMoveFinished")));
// Pew!
Context context = CCDirector.sharedDirector().getActivity();
SoundEngine.sharedEngine().playEffect(context, R.raw.pew_pew_lei);
return true;
}
public void gameLogic(float dt)
{
addTarget();
}
public void update(float dt)
{
ArrayList<CCSprite> projectilesToDelete = new ArrayList<CCSprite>();
for (CCSprite projectile : _projectiles)
{
CGRect projectileRect = CGRect.make(projectile.getPosition().x
- (projectile.getContentSize().width / 2.0f),
projectile.getPosition().y - (projectile.getContentSize().height / 2.0f),
projectile.getContentSize().width,
projectile.getContentSize().height);
ArrayList<CCSprite> targetsToDelete = new ArrayList<CCSprite>();
for (CCSprite target : _targets)
{
CGRect targetRect = CGRect.make(target.getPosition().x -
(target.getContentSize().width),
target.getPosition().y - (target.getContentSize().height),
target.getContentSize().width,
target.getContentSize().height);
if (CGRect.intersects(projectileRect, targetRect))
targetsToDelete.add(target);
}
for (CCSprite target : targetsToDelete)
{
_targets.remove(target);
removeChild(target, true);
}
if (targetsToDelete.size() > 0)
projectilesToDelete.add(projectile);
}
int k=0;
for (CCSprite projectile : projectilesToDelete)
{
_projectiles.remove(projectile);
removeChild(projectile, true);
if (++_projectilesDestroyed > 4)
{
_projectilesDestroyed = 0;
CCDirector.sharedDirector().replaceScene(GameOverLayer.
scene("You Win!",255,255,255,255));
nb=1;
/*Thread timer = new Thread() {
#Override
public void run() {
try {
sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// i add these lignes to pass to the next scene if the user wins
CCScene scene = GameLayer1.scene();
CCDirector.sharedDirector().runWithScene(scene);
}
}
};
timer.start();*/
}
}
}
protected void addTarget()
{
Random rand = new Random();
CCSprite target = CCSprite.sprite("Target.png");
// Determine where to spawn the target along the Y axis
CGSize winSize = CCDirector.sharedDirector().displaySize();
int minY = (int)(target.getContentSize().height / 2.0f);
int maxY = (int)(winSize.height - target.getContentSize().height / 2.0f);
int rangeY = maxY - minY;
int actualY = rand.nextInt(rangeY) + minY;
// Create the target slightly off-screen along the right edge,
// and along a random position along the Y axis as calculated above
target.setPosition(winSize.width + (target.getContentSize().width / 2.0f),
actualY);
addChild(target);
target.setTag(1);
_targets.add(target);
// Determine speed of the target
int minDuration = 2;
int maxDuration = 4;
int rangeDuration = maxDuration - minDuration;
int actualDuration = rand.nextInt(rangeDuration) + minDuration;
// Create the actions
CCMoveTo actionMove = CCMoveTo.action(actualDuration,
CGPoint.ccp(-target.getContentSize().width / 2.0f, actualY));
CCCallFuncN actionMoveDone = CCCallFuncN.action(this,
"spriteMoveFinished");
CCSequence actions = CCSequence.actions(actionMove, actionMoveDone);
target.runAction(actions);
}
public void spriteMoveFinished(Object sender)
{
CCSprite sprite = (CCSprite)sender;
if (sprite.getTag() == 1)
{
_targets.remove(sprite);
_projectilesDestroyed = 0;
CCDirector.sharedDirector().replaceScene(GameOverLayer.
scene("You Lose :(",255,255,255,255));
nb=0;
}
else if (sprite.getTag() == 2)
_projectiles.remove(sprite);
this.removeChild(sprite, true);
}
}
When the users wins the background changes but the new sprites never show up. How can I get the new sprites to show up as well?

CCMenuItem level1 = CCMenuItemLabel.item("Level 1", this, "level1");
CCMenuItem items[] = { level1};
CCMenu menu = CCMenu.menu(items);
menu.alignItemsVertically(50);
this.addChild(menu);
public void level1(Object sender) {
System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!");
CCScene scene = GameLayer.scene();
CCDirector.sharedDirector().pushScene(scene);
System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&");
}

CCDirector.sharedDirector().replaceScene(Level1.scene());

CCdirector.sharedDirector().runWithScene(scene);
Is this causing a syntax error?

Have you removed the current layer
removeFromParentAndCleanup(true);
or
removeSelf();
after that you can replace the scene
CCScene scene = GameLayer.scene();
CCDirector.sharedDirector().replaceScene(scene);
You have also to reset all variable to initial positions.

You have to use pushScene for next level
CCScene scene = GameLayerSec.scene();
CCDirector.sharedDirector().pushScene(scene);
GameLayerSec.scene() should be the next scene you designed for your next level.

Related

unable to make 2nd circle follow its own path

I am unable to create more circles which follows its own path with drawCircle .
I have used the code below which creates another circle but follows the path along the lines of 1st circle but not independent .How do I move both circles independent of each other?
I have added
c.drawCircle(ballX-100, ballY-100, 50, ballPaintyellow);
How do I make the above circle independent from the 1st circle?. I really appreciate any help.Thanks in Advance.
BouncingBallActivity.java
package com.stuffthathappens.games;
import static android.hardware.SensorManager.DATA_X;
import static android.hardware.SensorManager.DATA_Y;
import static android.hardware.SensorManager.SENSOR_ACCELEROMETER;
import static android.hardware.SensorManager.SENSOR_DELAY_GAME;
import java.util.concurrent.TimeUnit;
import android.app.Activity;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.hardware.SensorListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.SurfaceHolder.Callback;
/**
* This activity shows a ball that bounces around. The phone's
* accelerometer acts as gravity on the ball. When the ball hits
* the edge, it bounces back and triggers the phone vibrator.
*/
#SuppressWarnings("deprecation")
public class BouncingBallActivity extends Activity implements Callback, SensorListener {
private static final int BALL_RADIUS =20;
private SurfaceView surface;
private SurfaceHolder holder;
private final BouncingBallModel model = new BouncingBallModel(BALL_RADIUS);
private GameLoop gameLoop;
private Paint backgroundPaint;
private Paint ballPaint;
private SensorManager sensorMgr;
private long lastSensorUpdate = -1;
private Paint ballPaintyellow;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bouncing_ball);
surface = (SurfaceView) findViewById(R.id.bouncing_ball_surface);
holder = surface.getHolder();
surface.getHolder().addCallback(this);
backgroundPaint = new Paint();
backgroundPaint.setColor(Color.WHITE);
ballPaint = new Paint();
ballPaint.setColor(Color.BLUE);
ballPaint.setAntiAlias(true);
ballPaintyellow = new Paint();
ballPaintyellow.setColor(Color.YELLOW);
ballPaintyellow.setAntiAlias(true);
}
#Override
protected void onPause() {
super.onPause();
model.setVibrator(null);
sensorMgr.unregisterListener(this, SENSOR_ACCELEROMETER);
sensorMgr = null;
model.setAccel(0, 0);
}
#Override
protected void onResume() {
super.onResume();
sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
boolean accelSupported = sensorMgr.registerListener(this,
SENSOR_ACCELEROMETER,
SENSOR_DELAY_GAME);
if (!accelSupported) {
// on accelerometer on this device
sensorMgr.unregisterListener(this, SENSOR_ACCELEROMETER);
// TODO show an error
}
// NOTE 1: you cannot get system services before onCreate()
// NOTE 2: AndroidManifest.xml must contain this line:
// <uses-permission android:name="android.permission.VIBRATE"/>
Vibrator vibrator = (Vibrator) getSystemService(Activity.VIBRATOR_SERVICE);
model.setVibrator(vibrator);
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
model.setSize(width, height);
}
public void surfaceCreated(SurfaceHolder holder) {
gameLoop = new GameLoop();
gameLoop.start();
}
private void draw() {
// thread safety - the SurfaceView could go away while we are drawing
Canvas c = null;
try {
// NOTE: in the LunarLander they don't have any synchronization here,
// so I guess this is OK. It will return null if the holder is not ready
c = holder.lockCanvas();
// this needs to synchronize on something
if (c != null) {
doDraw(c);
}
} finally {
if (c != null) {
holder.unlockCanvasAndPost(c);
}
}
}
private void doDraw(Canvas c) {
int width = c.getWidth();
int height = c.getHeight();
c.drawRect(0, 0, width, height, backgroundPaint);
float ballX, ballY;
synchronized (model.LOCK) {
ballX = model.ballPixelX;
ballY = model.ballPixelY;
}
c.drawCircle(ballX, ballY, BALL_RADIUS, ballPaint);
c.drawCircle(ballX-100, ballY-100, 50, ballPaintyellow);
}
public void surfaceDestroyed(SurfaceHolder holder) {
try {
model.setSize(0,0);
gameLoop.safeStop();
} finally {
gameLoop = null;
}
}
private class GameLoop extends Thread {
private volatile boolean running = true;
public void run() {
while (running) {
try {
// don't like this hardcoding
TimeUnit.MILLISECONDS.sleep(5);
draw();
model.updatePhysics();
} catch (InterruptedException ie) {
running = false;
}
}
}
public void safeStop() {
running = false;
interrupt();
}
}
public void onAccuracyChanged(int sensor, int accuracy) {
}
public void onSensorChanged(int sensor, float[] values) {
if (sensor == SENSOR_ACCELEROMETER) {
long curTime = System.currentTimeMillis();
// only allow one update every 50ms, otherwise updates
// come way too fast
if (lastSensorUpdate == -1 || (curTime - lastSensorUpdate) > 50) {
lastSensorUpdate = curTime;
model.setAccel(values[DATA_X], values[DATA_Y]);
}
}
}
}
Bouncingballmodel.java
package com.stuffthathappens.games;
import java.util.concurrent.atomic.AtomicReference;
import android.os.Vibrator;
/**
* This data model tracks the width and height of the playing field along
* with the current position of a ball.
*/
public class BouncingBallModel {
// the ball speed is meters / second. When we draw to the screen,
// 1 pixel represents 1 meter. That ends up too slow, so multiply
// by this number. Bigger numbers speeds things up.
private final float pixelsPerMeter = 10;
private final int ballRadius;
// these are public, so make sure you synchronize on LOCK
// when reading these. I made them public since you need to
// get both X and Y in pairs, and this is more efficient than
// getter methods. With two getters, you'd still need to
// synchronize.
public float ballPixelX, ballPixelY;
private int pixelWidth, pixelHeight;
// values are in meters/second
private float velocityX, velocityY;
// typical values range from -10...10, but could be higher or lower if
// the user moves the phone rapidly
private float accelX, accelY;
/**
* When the ball hits an edge, multiply the velocity by the rebound.
* A value of 1.0 means the ball bounces with 100% efficiency. Lower
* numbers simulate balls that don't bounce very much.
*/
private static final float rebound = 0.8f;
// if the ball bounces and the velocity is less than this constant,
// stop bouncing.
private static final float STOP_BOUNCING_VELOCITY = 2f;
private volatile long lastTimeMs = -1;
public final Object LOCK = new Object();
private AtomicReference<Vibrator> vibratorRef =
new AtomicReference<Vibrator>();
public BouncingBallModel(int ballRadius) {
this.ballRadius = ballRadius;
}
public void setAccel(float ax, float ay) {
synchronized (LOCK) {
this.accelX = ax;
this.accelY = ay;
}
}
public void setSize(int width, int height) {
synchronized (LOCK) {
this.pixelWidth = width;
this.pixelHeight = height;
}
}
public int getBallRadius() {
return ballRadius;
}
/**
* Call this to move the ball to a particular location on the screen. This
* resets the velocity to zero, but the acceleration doesn't change so
* the ball should start falling shortly.
*/
public void moveBall(int ballX, int ballY) {
synchronized (LOCK) {
this.ballPixelX = ballX;
this.ballPixelY = ballY;
velocityX = 0;
velocityY = 0;
}
}
public void updatePhysics() {
// copy everything to local vars (hence the 'l' prefix)
float lWidth, lHeight, lBallX, lBallY, lAx, lAy, lVx, lVy;
synchronized (LOCK) {
lWidth = pixelWidth;
lHeight = pixelHeight;
lBallX = ballPixelX;
lBallY = ballPixelY;
lVx = velocityX;
lVy = velocityY;
lAx = accelX;
lAy = -accelY;
}
if (lWidth <= 0 || lHeight <= 0) {
// invalid width and height, nothing to do until the GUI comes up
return;
}
long curTime = System.currentTimeMillis();
if (lastTimeMs < 0) {
lastTimeMs = curTime;
return;
}
long elapsedMs = curTime - lastTimeMs;
lastTimeMs = curTime;
// update the velocity
// (divide by 1000 to convert ms to seconds)
// end result is meters / second
lVx += ((elapsedMs * lAx) / 1000) * pixelsPerMeter;
lVy += ((elapsedMs * lAy) / 1000) * pixelsPerMeter;
// update the position
// (velocity is meters/sec, so divide by 1000 again)
lBallX += ((lVx * elapsedMs) / 1000) * pixelsPerMeter;
lBallY += ((lVy * elapsedMs) / 1000) * pixelsPerMeter;
boolean bouncedX = false;
boolean bouncedY = false;
if (lBallY - ballRadius < 0) {
lBallY = ballRadius;
lVy = -lVy * rebound;
bouncedY = true;
} else if (lBallY + ballRadius > lHeight) {
lBallY = lHeight - ballRadius;
lVy = -lVy * rebound;
bouncedY = true;
}
if (bouncedY && Math.abs(lVy) < STOP_BOUNCING_VELOCITY) {
lVy = 0;
bouncedY = false;
}
if (lBallX - ballRadius < 0) {
lBallX = ballRadius;
lVx = -lVx * rebound;
bouncedX = true;
} else if (lBallX + ballRadius > lWidth) {
lBallX = lWidth - ballRadius;
lVx = -lVx * rebound;
bouncedX = true;
}
if (bouncedX && Math.abs(lVx) < STOP_BOUNCING_VELOCITY) {
lVx = 0;
bouncedX = false;
}
// safely copy local vars back to object fields
synchronized (LOCK) {
ballPixelX = lBallX;
ballPixelY = lBallY;
velocityX = lVx;
velocityY = lVy;
}
if (bouncedX || bouncedY) {
Vibrator v = vibratorRef.get();
if (v != null) {
v.vibrate(20L);
}
}
}
public void setVibrator(Vibrator v) {
vibratorRef.set(v);
}
}
Which view you are using has nothing to do with it ....
At the moment you have only one BouncingBallModel
private final BouncingBallModel model = new BouncingBallModel(BALL_RADIUS);
This is the one you see when you draw something. Now if you want to draw multiple balls, you will need many BouncingBallModel. So either create a BouncingBallModel model2 or make it dynamic using an array.
Then iterate over the array and draw each ball.

How to make "projectile"(bullets) to fire up when tapped or touched on the tip of the cannon in cocos2d android

I'm Developing android game app using Cocos2d-android game engine, in my game there is a cannon, when the player taps on the gamelayer "projectile" fires out, but according to my requirements when tapped on the tip of cannon "projectile" should come out, this can be done by using setposition of the cannon but here the cannons are rotatable, so got stuck up in giving the setposition.
Here's the code
public class GameL extends CCLayer{
protected LinkedList<CCSprite> _targets;
protected LinkedList<CCSprite> _projectiles;
protected int _projectilesDestroyed;
protected CCSprite _player;
protected CCSprite _nextProjectile;
public static CCScene scene()
{
CCScene scene = CCScene.node();
CCLayer layer = new GameL();
scene.addChild(layer);
return scene;
}
protected GameL()
{
this.setIsTouchEnabled(true);
_targets = new LinkedList<CCSprite>();
_projectiles = new LinkedList<CCSprite>();
_projectilesDestroyed = 0;
CCSprite background = CCSprite.sprite("bg.png");
background.setTag(1);
background.setAnchorPoint(0, 0);
addChild(background);
Context context = CCDirector.sharedDirector().getActivity();
CGSize winSize = CCDirector.sharedDirector().displaySize();
_player = CCSprite.sprite("gun2.png");
_player.setPosition(CGPoint.ccp(65,120));
// _player.setPosition(CGPoint.ccp(_player.getContentSize().width/2.0f, winSize.height/2.0f));
addChild(_player);
this.schedule("gameLogic", 1.0f);
this.schedule("update");
}
#Override
public boolean ccTouchesEnded(MotionEvent event)
{
// Choose one of the touches to work with
CGPoint location = CCDirector.sharedDirector().convertToGL(CGPoint.ccp(event.getX(), event.getY()));
// Set up initial location of projectile
CGSize winSize = CCDirector.sharedDirector().displaySize();
CCSprite _nextProjectile = CCSprite.sprite("firebl.png");
//_nextProjectile.setPosition(20, winSize.height / 2.0f);
_nextProjectile.setPosition(CGPoint.ccp(65, 120));
// Determine offset of location to projectile
int offX = (int)(location.x - _nextProjectile.getPosition().x);
int offY = (int)(location.y - _nextProjectile.getPosition().y);
// Bail out if we are shooting down or backwards
if (offX <= 0)
return true;
_nextProjectile.setTag(2);
// Determine where we wish to shoot the projectile to
int realX = (int)(winSize.width + (_nextProjectile.getContentSize().width / 2.0f));
float ratio = (float)offY / (float)offX;
int realY = (int)((realX * ratio) + _nextProjectile.getPosition().y);
CGPoint realDest = CGPoint.ccp(realX, realY);
// Determine the length of how far we're shooting
int offRealX = (int)(realX - _nextProjectile.getPosition().x);
int offRealY = (int)(realY - _nextProjectile.getPosition().y);
float length = FloatMath.sqrt((offRealX * offRealX) + (offRealY * offRealY));
float velocity = 480.0f / 1.0f; // 480 pixels / 1 sec
float realMoveDuration = length / velocity;
// Move projectile to actual endpoint
_nextProjectile.runAction(CCSequence.actions(
CCMoveTo.action(realMoveDuration, realDest),
CCCallFuncN.action(this, "spriteMoveFinished")));
// Determine angle to face
double angleRadians = Math.atan((double)offRealY / (double)offRealX);
double angleDegrees = Math.toDegrees(angleRadians);
double cocosAngle = -1 * angleDegrees;
double rotationSpeed = 0.5 / Math.PI;
double rotationDuration = Math.abs(angleRadians * rotationSpeed);
_player.runAction(CCSequence.actions(
CCRotateTo.action((float)rotationDuration, (float)cocosAngle),
CCCallFunc.action(this, "finishShoot")));
// Pew!
Context context = CCDirector.sharedDirector().getActivity();
SoundEngine.sharedEngine().playEffect(context, R.raw.pew_pew_lei);
return true;
}
public void finishShoot()
{
addChild(_nextProjectile);
_projectiles.add(_nextProjectile);
}
public void gameLogic(float dt)
{
addTarget();
}
public void update(float dt)
{
LinkedList<CCSprite> projectilesToDelete = new LinkedList<CCSprite>();
for (CCSprite projectile : _projectiles)
{
CGRect projectileRect = CGRect.make(projectile.getPosition().x - (projectile.getContentSize().width / 2.0f),
projectile.getPosition().y - (projectile.getContentSize().height / 2.0f),
projectile.getContentSize().width,
projectile.getContentSize().height);
LinkedList<CCSprite> targetsToDelete = new LinkedList<CCSprite>();
for (CCSprite target : _targets)
{
CGRect targetRect = CGRect.make(target.getPosition().x - (target.getContentSize().width),
target.getPosition().y - (target.getContentSize().height),
target.getContentSize().width,
target.getContentSize().height);
if (CGRect.intersects(projectileRect, targetRect))
targetsToDelete.add(target);
}
for (CCSprite target : targetsToDelete)
{
_targets.remove(target);
removeChild(target, true);
}
if (targetsToDelete.size() > 0)
projectilesToDelete.add(projectile);
}
for (CCSprite projectile : projectilesToDelete)
{
_projectiles.remove(projectile);
removeChild(projectile, true);
if (++_projectilesDestroyed > 30)
{
_projectilesDestroyed = 0;
CCDirector.sharedDirector().replaceScene(Gameoverlayer.scene("You Win!"));
}
}
}
Probably you have to add condition of the canon sprite and touch location replace the below code with touchBegan
public boolean ccTouchesBegan(MotionEvent event)
{
CGPoint location = CCDirector.sharedDirector().convertToGL(CGPoint.ccp(event.getX(), event.getY()));
// Set up initial location of projectile
CGSize winSize = CCDirector.sharedDirector().displaySize();
_nextProjectile = CCSprite.sprite("fireball50.png");
// _nextProjectile.setPosition(20, winSize.height / 2.0f);
_nextProjectile.setPosition(CGPoint.ccp(65, 120));
for (CCSprite target : targets)
{
if (CGRect.containsPoint((target.getBoundingBox()), location))
{
// Determine offset of location to projectile
int offX = (int) (location.x - _nextProjectile.getPosition().x);
int offY = (int) (location.y - _nextProjectile.getPosition().y);
// Bail out if we are shooting down or backwards
_nextProjectile.setTag(3);
// Determine where we wish to shoot the projectile
// to
int realX = (int) (winSize.width + (_nextProjectile.getContentSize().width / 2.0f));
float ratio = (float) offY / (float) offX;
int realY = (int) ((realX * ratio) + _nextProjectile.getPosition().y);
CGPoint realDest = CGPoint.ccp(realX, realY);
// Determine the length of how far we're shooting
int offRealX = (int) (realX - _nextProjectile.getPosition().x);
int offRealY = (int) (realY - _nextProjectile.getPosition().y);
float length = FloatMath.sqrt((offRealX * offRealX) + (offRealY * offRealY));
float velocity = 480.0f / 1.0f; // 480 pixels / 1
// sec
float realMoveDuration = length / velocity;
System.out.println(" - t tag!!!!!!!!!!!!!!!!!!!!! - ");
_nextProjectile.runAction(CCSequence.actions(CCMoveTo.action(realMoveDuration, realDest),
CCCallFuncN.action(this, "spriteMoveFinished")));
double angleRadians = Math.atan((double) offRealY / (double) offRealX);
double angleDegrees = Math.toDegrees(angleRadians);
double cocosAngle = -1 * angleDegrees;
double rotationSpeed = 0.5 / Math.PI;
double rotationDuration = Math.abs(angleRadians * rotationSpeed);
target.runAction(CCSequence.actions(
CCRotateTo.action((float) rotationDuration, (float) cocosAngle),
CCCallFunc.action(this, "finishShoot")));
break;
}
}
return true;
}
I honestly admit I never used Cocos2d-android game-engine,
but I hope I can provide some help.
At first what you said in the comment is the following: You touch anywhere on the screen and then the cannon fires, but what you want is to only make a projectile fire when the cannon is touched.
Everytime you touch the screen public boolean ccTouchesEnded(MotionEvent event) is called.
If you add an if statement at the top of the ccTouchesEnded function which checks if the touch is within the scope of where the cannon is placed it might do the trick. The coordinates of where the screen is touched is presumably in the MotionEvent object provided by the function.
So the following pseudocode might do the trick:
NOTE: I assume the coordinates of the image is the Left Under Corner
public boolean ccTouchesEnded(MotionEvent event)
{
if(event.isTouchedOnX() < CannonX
|| event.isTouchedOnX() > CannonX + horizontalSizeOfCannonImage
|| event.isTouchedOnY() < CannonY
|| event.isTouchedOnY() > CannonY + verticalsizeOfCannonImage)
{
// Don't do a thing and see the event as processed
return true; // You might want to check what the boolean returning the function really means but it might presumably mean that the event does not need further processing by the window.
}
... The rest of the code.
}
I really hope this will help you!
Christian

animation with cocos2d android

I doing animation with framework cocos2d android.I have series image same blow image, I want to crop a tivi in image use to cocos2d in android. Plz help me?
link image
public class MainActivity extends Activity {
private static final boolean DEBUG = true;
private CCGLSurfaceView mGLSurfaceView;
static Context context;
static Resources resources;
static AssetManager assetManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
mGLSurfaceView = new CCGLSurfaceView(this);
setContentView(mGLSurfaceView);
assetManager = getAssets();
}
#Override
protected void onStart() {
super.onStart();
// attach the OpenGL view to a Window
Director.sharedDirector().attachInView(mGLSurfaceView);
// set landscape mode
// Director.sharedDirector().setLandscape(true);
// show FPS
Director.sharedDirector().setDisplayFPS(true);
// frames per second
Director.sharedDirector().setAnimationInterval(1.0f / 60);
Scene scene = Scene.node();
scene.addChild(nextAction());
// Make the scene active
Director.sharedDirector().runWithScene(scene);
}
static int sceneIdx = -1;
static Class transitions[] = { Animation1.class, };
static Layer nextAction() {
sceneIdx++;
sceneIdx = sceneIdx % transitions.length;
return restartAction();
}
static Layer restartAction() {
try {
Class c = transitions[sceneIdx];
return (Layer) c.newInstance();
} catch (Exception e) {
if (DEBUG)
e.printStackTrace();
return null;
}
}
#Override
protected void onPause() {
super.onPause();
Director.sharedDirector().pause();
}
#Override
protected void onResume() {
super.onResume();
Director.sharedDirector().resume();
}
#Override
protected void onDestroy() {
super.onDestroy();
TextureManager.sharedTextureManager().removeAllTextures();
}
static class Anima extends Layer {
Sprite tivi;
Sprite bg2;
InputStream is;
Resources resources;
AssetManager asset;
Bitmap bf, bitmap, bitmap2;
CCSize s = Director.sharedDirector().displaySize();
public Anima() {
Log.v("MP", "Width: " + s.width + " Height: " + s.height);
bg2 = Sprite.sprite("Scene02.png");
bg2.setScaleX(s.width / bg2.getTexture().getWidth());
bg2.setScaleY(s.height / bg2.getTexture().getHeight());
bg2.setPosition(s.width / 2, s.height / 2);
addChild(bg2, 1);
tivi = Sprite.sprite("TV0000.png");
tivi.setScaleX(s.width / bg2.getTexture().getWidth());
tivi.setScaleY(s.height / bg2.getTexture().getHeight());
//tivi.setPosition(0, 0);
tivi.setPosition(247 * s.width / bg2.getTexture().getWidth(), 480
* s.height / bg2.getTexture().getHeight());
addChild(tivi, 1);
}
protected void centerSprites() {
// tivi.setPosition(247 * s.width / bg2.getTexture().getWidth(), 480
// * s.height / bg2.getTexture().getHeight());
}
}
static class Animation1 extends Anima {
Animation tvAnimation;
IntervalAction tvAction;
CCSize s = Director.sharedDirector().displaySize();
boolean ck = true;
public Animation1() {
// centerSprites();
isTouchEnabled_ = true;
tvAnimation = initTVAnimation();
tvAction = Animate.action(tvAnimation);
}
private Animation initTVAnimation() {
Animation animation = new Animation("abc", 0.2f);
for (int i = 1; i < 40; i++) {
try {
is = assetManager.open(new CCFormatter().format(
"TV00%02d.png", i));
bf = BitmapFactory.decodeStream(is);
bitmap = Bitmap.createBitmap(bf, 0, 0, bf.getWidth(),
bf.getHeight());
bitmap2 = Bitmap
.createBitmap(bitmap, (int) (153 * (s.width / bg2
.getTexture().getWidth())),
(int) (261.5 * (s.height / bg2.getTexture()
.getHeight())),
(int) (87 * (s.width / bg2.getTexture()
.getWidth())),
(int) (97 * (s.height / bg2.getTexture()
.getHeight())));
animation.addFrame(bitmap2);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return animation;
}
#Override
public boolean ccTouchesBegan(MotionEvent event) {
CCSize s = Director.sharedDirector().displaySize();
CCPoint location = Director.sharedDirector().convertToGL(
event.getX(), event.getY());
if ((location.x >= 203.5 * s.width / bg2.getTexture().getWidth() && location.x <= 290
* s.width / bg2.getTexture().getWidth())
&& (location.y >= 433.5 * s.height
/ bg2.getTexture().getHeight() && location.y <= 526
* s.height / bg2.getTexture().getHeight())) {
if (tvAction.isDone() == true || ck == true) {
tivi.runAction(tvAction);
ck = false;
}
}
// addNew(location);
return TouchDispatcher.kEventHandled;
}
}
}
Animation animation = new Animation("abc", 0.2f);
for (int i = 1; i < 40; i++) {
try {
is = assetManager.open(new CCFormatter().format(
"TV00%02d.png", i));
bf = BitmapFactory.decodeStream(is);
bitmap = Bitmap.createBitmap(bf, 0, 0, bf.getWidth(),
bf.getHeight());
bitmap2 = Bitmap
.createBitmap(bitmap, (int) (153 * (s.width / bg2
.getTexture().getWidth())),
(int) (261.5 * (s.height / bg2.getTexture()
.getHeight())),
(int) (87 * (s.width / bg2.getTexture()
.getWidth())),
(int) (97 * (s.height / bg2.getTexture()
.getHeight())));
animation.addFrame(bitmap2);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return animation;
}
try to make simple of this code.... use the latest example series from the cocs2d-android 1 .. it have basic concept for handing the animation ..... you will get the answer from the example series
Hai i hope this will help you lot. I have used CCSprite. it scale to support all Screens with animation. scaling CCSprite in 480x800
public class MainMenuScreen extends CCColorLayer {
private CCSprite newGame1;
private CGSize size; // this is where we hold the size of current display
private float scaleX, scaleY;// these are the ratios that we need to compute
public static CCScene sence() {
CCScene ccScene = CCScene.node();
CCLayer layer = new MainMenuScreen(ccColor4B.ccc4(69, 3, 3, 255));
ccScene.addChild(layer);
return ccScene;
}
protected MainMenuScreen(ccColor4B color) {
super(color);
size = CCDirector.sharedDirector().winSize();
CCSprite backGround = CCSprite
.sprite(CandygrabberImage.MENU_BACKGROUND);
this.setIsTouchEnabled(true);
// backGround.setContentSize(winSize);
backGround.setTag(1);
backGround.setScale(.5f);
backGround.setPosition(CGPoint.ccp(size.width / 2.0f,
size.height / 2.0f));
backGround
.setScaleX(size.width / backGround.getTexture().getWidth());
backGround.setScaleY(size.height
/ backGround.getTexture().getHeight());
addChild(backGround);
scaleX = size.width / 480f;// assuming that all my assets are available
// for a 320X480(landscape) resolution;
scaleY = size.height / 800f;
newGame1 = CCSprite.sprite("newgame1.png");
CCAnimation buttonAnimation = CCAnimation.animation("", 1f);
buttonAnimation.addFrame("newgame1.png");
buttonAnimation.addFrame("newgame2.png");
buttonAnimation.addFrame("newgame3.png");
buttonAnimation.addFrame("newgame4.png");
buttonAnimation.addFrame("newgame5.png");
buttonAnimation.addFrame("newgame6.png");
buttonAnimation.addFrame("newgame7.png");
buttonAnimation.addFrame("newgame8.png");
CCIntervalAction buttonAction = CCAnimate.action(5, buttonAnimation,
false);
newGame1.runAction(CCRepeatForever.action(buttonAction));
newGame1.setScaleX(scaleX);
newGame1.setScaleY(scaleY);
newGame1.setScale(aspect_Scale(newGame1, scaleX, scaleY));
this.addChild(newGame1);
this.setIsTouchEnabled(true);
}
public float aspect_Scale(CCSprite sprite, float scaleX, float scaleY) {
float sourcewidth = sprite.getContentSize().width;
float sourceheight = sprite.getContentSize().height;
float targetwidth = sourcewidth * scaleX;
float targetheight = sourceheight * scaleY;
float scalex = (float) targetwidth / sourcewidth;
float scaley = (float) targetheight / sourceheight;
return Math.min(scalex, scaley);
}
}

Remove continuous spawn sprite when touched

I am new with AndEngine. I just created a scene with many spawned sprites that come from above screen height in landscape mode. Now I want to remove a sprite when I touch on it. Problem is, when I touched the screen the most recent sprite is removed and I can't remove the tapped sprite individually.
Here is my code:
//======== TimerHandler for collision detection and cleaning up ======
IUpdateHandler detect = new IUpdateHandler() {
#Override
public void reset() {
}
#Override
public void onUpdate(float pSecondsElapsed) {
targets = targetLL.iterator();
while (targets.hasNext()) {
_target = targets.next();
if (_target.getY() >= cameraHeight) {
// removeSprite(_target, targets);
tPool.recyclePoolItem(_target);
targets.remove();
Log.d("ok", "---------Looop Inside-----");
// fail();
break;
}
// i don't know whether below code is valid for this postion
mMainScene.setOnSceneTouchListener(new IOnSceneTouchListener() {
#Override
public boolean onSceneTouchEvent(Scene arg0,
TouchEvent pSceneTouchEvent) {
try {
// i can't use this two
final float touchX = pSceneTouchEvent.getX();
final float touchY = pSceneTouchEvent.getY();
if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_DOWN) {
//call to remove sprite
removeSprite(_target, targets);
}
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
});
}
targetLL.addAll(TargetsToBeAdded);
TargetsToBeAdded.clear();
}
};
code for adding target:
/** adds a target at a random location and let it move along the y-axis */
public void addTarget() {
Random rand = new Random();
int minX = mTargetTextureRegion.getWidth();
int maxX = (int) (mCamera.getWidth() - mTargetTextureRegion.getWidth());
int rangeX = maxX - minX;
Log.d("----point----", "minX:" + minX + "maxX:" + maxX + "rangeX:"
+ rangeX);
int rX = rand.nextInt(rangeX) + minX;
int rY = (int) mCamera.getHeight() + mTargetTextureRegion.getHeight();
Log.d("---Random x----", "Random x" + rX + "Random y" + rY);
//HERE I USE POOL TO CREATE NEW SPRITE
//tPool is object of TargetsPool Class
target = tPool.obtainPoolItem();
target.setPosition(rX, rY);
target.animate(100);
mMainScene.attachChild(target, 1);
mMainScene.registerTouchArea(target);
int minDuration = 2;
int maxDuration = 32;
int rangeDuration = maxDuration - minDuration;
int actualDuration = rand.nextInt(rangeDuration) + minDuration;
// MoveXModifier mod = new MoveXModifier(actualDuration, target.getX(),
// -target.getWidth());
MoveYModifier mody = new MoveYModifier(actualDuration,
-target.getHeight(), cameraHeight + 10);
target.registerEntityModifier(mody.deepCopy());
TargetsToBeAdded.add(target);
}
code for remove sprite when touched:
// ==============the method to remove sprite=====================
public void removeSprite(final AnimatedSprite _sprite, Iterator it) {
runOnUpdateThread(new Runnable() {
#Override
public void run() {
_target = _sprite;
mMainScene.detachChild(_target);
}
});
it.remove();
}
I use GenericPool to create new sprite.
I am not sure where I have to write code for the specific touched sprite and remove it.
ohh.. I found the solution here.
I implemented an IOnAreaTouchListener in BaseGameActivity class. So, my class declaration looks like:
public class CrazyMonkeyActivity extends BaseGameActivity implements
IOnAreaTouchListener
and my override method looks like:
#Override
public boolean onAreaTouched(final TouchEvent pSceneTouchEvent,
final ITouchArea pTouchArea, final float pTouchAreaLocalX,
final float pTouchAreaLocalY) {
if (pSceneTouchEvent.isActionDown()) {
this.removeSprite((AnimatedSprite) pTouchArea);
return true;
}
return false;
}
And remove Sprite methods should be like:
// ==============the method to remove spirit=====================
public void removeSprite(final AnimatedSprite target) {
runOnUpdateThread(new Runnable() {
#Override
public void run() {
mMainScene.detachChild(target);
mMainScene.unregisterTouchArea(target);
System.gc();
}
});
}
To create continuous Spawn Sprite I use a time handler inside this method. Below method should be called inside onLoadScene() method:
/** a Time Handler for spawning targets Sprites, triggers every 2 second */
private void createSpriteSpawnTimeHandler() {
TimerHandler spriteTimerHandler;
float mEffectSpawnDelay = 2f;
spriteTimerHandler = new TimerHandler(mEffectSpawnDelay, true,
new ITimerCallback() {
#Override
public void onTimePassed(TimerHandler pTimerHandler) {
//position for random sprite
final float xPos = MathUtils.random(30.0f,
(cameraWidth - 30.0f));
final float yPos = MathUtils.random(30.0f,
(cameraHeight - 30.0f));
//below method call for new sprite
addTarget(xPos, yPos);
}
});
getEngine().registerUpdateHandler(spriteTimerHandler);
}
And addTarget() looks like:
public void addTarget(float xPos, float yPos) {
Random rand = new Random();
Log.d("---Random x----", "Random x" + xPos + "Random y" + yPos);
target = new AnimatedSprite(xPos, yPos, mTargetTextureRegion);
target.animate(100);
mMainScene.attachChild(target);
mMainScene.registerTouchArea(target);
int minDuration = 2;
int maxDuration = 32;
int rangeDuration = maxDuration - minDuration;
int actualDuration = rand.nextInt(rangeDuration) + minDuration;
MoveYModifier mody = new MoveYModifier(actualDuration,
-target.getHeight(), cameraHeight + 10);
target.registerEntityModifier(mody.deepCopy());
}
Hope this might help others too!

move from one scene to another with cocos 2D in android (multi-level)

I want to make a game with levels.that's means in the first level the user have to kill some targets if he wins he pass to the next level with new targets and new background. I use this game tuto!
i have these classes ---->
package game.wael.ialhi;
import org.cocos2d.layers.CCScene;
import org.cocos2d.nodes.CCDirector;
import org.cocos2d.opengl.CCGLSurfaceView;
import org.cocos2d.sound.SoundEngine;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
public class SimpleGame extends Activity{
protected CCGLSurfaceView _glSurfaceView;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
_glSurfaceView = new CCGLSurfaceView(this);
setContentView(_glSurfaceView);
}
#Override
public void onStart()
{
super.onStart();
CCDirector.sharedDirector().attachInView(_glSurfaceView);
CCDirector.sharedDirector().setDeviceOrientation(CCDirector
.kCCDeviceOrientationLandscapeLeft);
CCDirector.sharedDirector().setDisplayFPS(true);
CCDirector.sharedDirector().setAnimationInterval(1.0f / 60.0f);
CCScene scene = GameLayer.scene();
CCDirector.sharedDirector().runWithScene(scene);
}
#Override
public void onPause(){
super.onPause();
CCDirector.sharedDirector().pause();
SoundEngine.sharedEngine().stopSound();
}
#Override
public void onResume(){
super.onResume();
CCDirector.sharedDirector().resume();
}
#Override
public void onStop(){
super.onStop();
CCDirector.sharedDirector().end();
SoundEngine.sharedEngine().stopSound();
}
}
i make some modification in this GameLayer class.in the update methode i add these ligne so that when the user wins he pass to the next scene (GameLayer1) ---->
CCScene scene=GameLayer1.scene();
CCDirector.sharedDirector().runWithScene(scene);
and this the complete class ------>
package game.wael.ialhi;
public class GameLayer extends CCColorLayer{
protected ArrayList<CCSprite> _targets;
protected ArrayList<CCSprite> _projectiles;
protected int _projectilesDestroyed;
public static int nb;
public static CCScene scene() {
CCScene scene = CCScene.node();
CCColorLayer layer = new GameLayer(ccColor4B.ccc4(255, 255, 255, 255));
scene.addChild(layer);
return scene;
}
protected GameLayer(ccColor4B color){
super(color);
this.setIsTouchEnabled(true);
_targets = new ArrayList<CCSprite>();
_projectiles = new ArrayList<CCSprite>();
_projectilesDestroyed = 0;
CGSize winSize = CCDirector.sharedDirector().displaySize();
CCSprite player = CCSprite.sprite("Player.png");
player.setPosition(CGPoint.ccp(player.getContentSize().width / 2.0f,
winSize.height / 2.0f));
addChild(player);
// Handle sound
Context context = CCDirector.sharedDirector().getActivity();
SoundEngine.sharedEngine().preloadEffect(context, R.raw.pew_pew_lei);
SoundEngine.sharedEngine().playSound(context, R.raw.background_music_aac,
true);
this.schedule("gameLogic", 1.0f);
this.schedule("update");
}
#Override
public boolean ccTouchesEnded(MotionEvent event){
// Choose one of the touches to work with
CGPoint location =
CCDirector.sharedDirector().convertToGL(CGPoint.ccp(event.getX(),
event.getY()));
// Set up initial location of projectile
CGSize winSize = CCDirector.sharedDirector().displaySize();
CCSprite projectile = CCSprite.sprite("Projectile.png");
projectile.setPosition(20, winSize.height / 2.0f);
// Determine offset of location to projectile
int offX = (int)(location.x - projectile.getPosition().x);
int offY = (int)(location.y - projectile.getPosition().y);
// Bail out if we are shooting down or backwards
if (offX <= 0)
return true;
// Ok to add now - we've double checked position
addChild(projectile);
projectile.setTag(2);
_projectiles.add(projectile);
// Determine where we wish to shoot the projectile to
int realX = (int)(winSize.width + (projectile.getContentSize().width /
2.0f));
float ratio = (float)offY / (float)offX;
int realY = (int)((realX * ratio) + projectile.getPosition().y);
CGPoint realDest = CGPoint.ccp(realX, realY);
// Determine the length of how far we're shooting
int offRealX = (int)(realX - projectile.getPosition().x);
int offRealY = (int)(realY - projectile.getPosition().y);
float length = (float)Math.sqrt((offRealX * offRealX) + (offRealY *
offRealY));
float velocity = 480.0f / 1.0f; // 480 pixels / 1 sec
float realMoveDuration = length / velocity;
// Move projectile to actual endpoint
projectile.runAction(CCSequence.actions(
CCMoveTo.action(realMoveDuration, realDest),
CCCallFuncN.action(this, "spriteMoveFinished")));
// Pew!
Context context = CCDirector.sharedDirector().getActivity();
SoundEngine.sharedEngine().playEffect(context, R.raw.pew_pew_lei);
return true;
}
public void gameLogic(float dt){
addTarget();
}
public void update(float dt){
ArrayList<CCSprite> projectilesToDelete = new ArrayList<CCSprite>();
for (CCSprite projectile : _projectiles)
{
CGRect projectileRect = CGRect.make(projectile.getPosition().x
- (projectile.getContentSize().width / 2.0f),
projectile.getPosition().y -
(projectile.getContentSize().height / 2.0f),
projectile.getContentSize().width,
projectile.getContentSize().height);
ArrayList<CCSprite> targetsToDelete = new ArrayList<CCSprite>();
for (CCSprite target : _targets)
{
CGRect targetRect = CGRect.make(target.getPosition().x -
(target.getContentSize().width),
target.getPosition().y -
(target.getContentSize().height),
target.getContentSize().width,
target.getContentSize().height);
if (CGRect.intersects(projectileRect, targetRect))
targetsToDelete.add(target);
}
for (CCSprite target : targetsToDelete)
{
_targets.remove(target);
removeChild(target, true);
}
if (targetsToDelete.size() > 0)
projectilesToDelete.add(projectile);
}
int k=0;
for (CCSprite projectile : projectilesToDelete)
{
_projectiles.remove(projectile);
removeChild(projectile, true);
if (++_projectilesDestroyed > 4)
{
_projectilesDestroyed = 0;
CCDirector.sharedDirector().replaceScene(GameOverLayer.
scene("You Win!",255,255,255,255));
nb=1;
/*Thread timer = new Thread() {
#Override
public void run() {
try {
sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// i add these lignes to pass to the next scene if the user wins
CCScene scene = GameLayer1.scene();
CCDirector.sharedDirector().runWithScene(scene);
}
}
};
timer.start();*/
}
}
}
protected void addTarget(){
Random rand = new Random();
CCSprite target = CCSprite.sprite("Target.png");
// Determine where to spawn the target along the Y axis
CGSize winSize = CCDirector.sharedDirector().displaySize();
int minY = (int)(target.getContentSize().height / 2.0f);
int maxY = (int)(winSize.height - target.getContentSize().height / 2.0f);
int rangeY = maxY - minY;
int actualY = rand.nextInt(rangeY) + minY;
// Create the target slightly off-screen along the right edge,
// and along a random position along the Y axis as calculated above
target.setPosition(winSize.width + (target.getContentSize().width / 2.0f),
actualY);
addChild(target);
target.setTag(1);
_targets.add(target);
// Determine speed of the target
int minDuration = 2;
int maxDuration = 4;
int rangeDuration = maxDuration - minDuration;
int actualDuration = rand.nextInt(rangeDuration) + minDuration;
// Create the actions
CCMoveTo actionMove = CCMoveTo.action(actualDuration,
CGPoint.ccp(-target.getContentSize().width / 2.0f, actualY));
CCCallFuncN actionMoveDone = CCCallFuncN.action(this,
"spriteMoveFinished");
CCSequence actions = CCSequence.actions(actionMove, actionMoveDone);
target.runAction(actions);
}
public void spriteMoveFinished(Object sender){
CCSprite sprite = (CCSprite)sender;
if (sprite.getTag() == 1)
{
_targets.remove(sprite);
_projectilesDestroyed = 0;
CCDirector.sharedDirector().replaceScene(GameOverLayer.
scene("You Lose :(",255,255,255,255));
nb=0;
}
else if (sprite.getTag() == 2)
_projectiles.remove(sprite);
this.removeChild(sprite, true);
}
}
But when the user wins only the background changes, the new sprites never show up..
help please
I hope this will help you. I need to create Level2.class and change the background image. set the level value in a class with getter and setter.
if (Score.getLevel() == 1) {
CCScene scene = Level2.scene();
CCDirector.sharedDirector().replaceScene(
CCSlideInRTransition.transition(.5f, scene));
}
Set the Level value form the Level screen.

Categories

Resources