I Have already completed the bluetooth CHAT Example on android developer, now i am designing a game and need to transfer the coordinates between the devices. I am using cocos2d and now how to send the data via bluetooth on other device. i need to apply the bluetooth chat application in this game but how? i cant understand how to achieve it. Any Suggestions greatly appreciated ...please ask any questions if u dont get what i am trying to ask...
public boolean ccTouchesEnded(MotionEvent event)
{
boolean get=false;
//int y=0;
// Choose one of the touches to work with
CGPointlocation=CCDirector.sharedDirector().convertToGL(CGPoint.ccp(event.getX(),event.get;
if(y==0)
{get=shootarrow(location);
y=1;
return get;}
else if(y==1)
{get=shootme(location);
y=0;
return get;
}
return get;
}
public boolean shootme(CGPoint loc){
// Set up initial location of projectile
CGSize winSize = CCDirector.sharedDirector().displaySize();
CCSprite projectile = CCSprite.sprite("ah2.png");
projectile.setPosition(CGPoint.ccp(650,180));
CCSprite player2 = CCSprite.sprite("Ply2.png");
player2.setPosition(CGPoint.ccp(winSize.width / 2.0f,320));
// Determine offset of location to projectile
int offX = (int)(loc.x - projectile.getPosition().x);
int offY = (int)(loc.y - projectile.getPosition().y);
if (offX >= 0)
return true;
if (offY <= -7)
return true;
addChild(projectile);
addChild(player2);
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 = 680.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")));
Context context = CCDirector.sharedDirector().getActivity();
return true;
}
Related
I'm creating a AR game with ARfoundation where the player can swipe a ball to whatever direction.
The problem I encounter is that when the ball is spawned the first time all the other balls that are spawned, will load on the same position as the first ball whatever direction I'm aiming at with my camera.
I want it to get it always spawned in front of the camera no matter the location, position and direction of my phone's camera. Tried using tags to get the location of the camera en the cup of where the ball need to get thrown in but still the ball doesn't get loaded in front of the camera no matter the location. I guess this is not the right way to achieve this and I was wondering what is?
The code I'm using for spawning the ball on a certain location
[SerializeField]
GameObject ball;
public float distanceX;
public float distanceY;
public float distanceZ;
public float ballX;
public float ballY;
public float ballZ;
public void Spawn()
{
distanceX = GameObject.FindGameObjectWithTag("Cup").transform.position.x - GameObject.FindGameObjectWithTag("MainCamera").transform.position.x;
distanceY = GameObject.FindGameObjectWithTag("Cup").transform.position.y - GameObject.FindGameObjectWithTag("MainCamera").transform.position.y;
distanceZ = GameObject.FindGameObjectWithTag("Cup").transform.position.z - GameObject.FindGameObjectWithTag("MainCamera").transform.position.z;
ballX = distanceX / 4;
ballY = distanceY / 4;
ballZ = distanceZ / 4;
Instantiate(ball, new Vector3(ballX, ballY, 10f), Quaternion.identity);
}
A bit hard to tell how your camera and this Cup Object are related and where exactly your object shall be spawned.
But in general for spawning something in front of your main camera you can do e.g.
public void Spawn()
{
// this basically does FindObjectWithTag("Main camera")
var camera = Camera.main.transform;
Instantiate(ball, camera.position + camera.forward * 10f, Quaternion.identity);
}
If you need a different distance then 10 e.g. based on that Cup object you just replace that or add another offset vector.
Either way you should not store it in individual floats just to build a new vector again ;)
E.g. instead of
distanceX = GameObject.FindGameObjectWithTag("Cup").transform.position.x - GameObject.FindGameObjectWithTag("MainCamera").transform.position.x;
distanceY = GameObject.FindGameObjectWithTag("Cup").transform.position.y - GameObject.FindGameObjectWithTag("MainCamera").transform.position.y;
distanceZ = GameObject.FindGameObjectWithTag("Cup").transform.position.z - GameObject.FindGameObjectWithTag("MainCamera").transform.position.z;
ballX = distanceX / 4;
ballY = distanceY / 4;
ballZ = distanceZ / 4;
you would rather do
Vevtor3 distance = GameObject.FindGameObjectWithTag("Cup").transform.position - GameObject.FindGameObjectWithTag("MainCamera").transform.position;
Vector3 ballDelta = distanceX / 4f;
...
Im trying to build a simple Music Visualisation App which just should resize a Circle. So if the Music Part which is currently playing is loud it should get bigger and if not it should get smaller.
To Visualize the Circle I just created a custom View Class which draws the circle in the onDraw Method.
To get the informations out of the current Audio, I found the Visualizer Class of Android and also used the setDataCaptureListener.
mVisualizer = new Visualizer(mMediaPlayer.getAudioSessionId());
mVisualizer.setCaptureSize(Visualizer.getCaptureSizeRange()[0]);
mVisualizer.setDataCaptureListener(
new Visualizer.OnDataCaptureListener() {
public void onWaveFormDataCapture(Visualizer visualizer,byte[] bytes, int samplingRate) {
mVisualizerView.updateVisualizer(bytes);
}
public void onFftDataCapture(Visualizer visualizer,byte[] bytes, int samplingRate) {
}
}, (int)(Visualizer.getMaxCaptureRate() / 1.5), true, false);
But my Problem is that I don't really know how I use the byte Array which is given back, to find out the music change in general (got louder or not ?).
I just tried to get the average of the array but this gives me completely bad results. The circle changed his size like it is on drugs. So I thought maybe the array has too many outlined/extreme values (which was true) so I calculated the median of the array. This gaved me better results but still isn't what I want. It's not very smooth and it's to complex. I always have to sort the array which is not really efficient. What am I thinking wrong ?
Im really a beginner in this AudioFX section and Im completely sorry If this is a dumb question and attempt of me.
Thank you for your help !
EDIT:
private float schwelle = 5000;
private float last = 0;
...
float summe = 0;
for (Byte currentByte: mBytes)
summe += currentByte;
if (summe > schwelle && summe > last)
{
last = summe; //make it bigger
}
else {
last -= 100; //make circle smaller
}
canvas.drawCircle(getWidth()/2,getHeight()/2,last / 100,mForePaint);
A really good git project is https://github.com/felixpalmer/android-visualizer.
I myself came up with this:(it's a lot simple than the git solution)
You can use the values of the array to draw the the waveform on the outline of a circle using trigonometry, and make the start radius of the circle bigger if the sum of the array is bigger than certain treshhold:
class StarWaveformRenderer implements Renderer {
private Paint p = new Paint();
private static final int BOOST_TRASH_HOLD = 10000;
private float stretchFade = 1; //circle fades after a prominent beat
#Override
public void render(Canvas canvas, byte[] data) {
if (data == null || data.length == 0)
return;
int centerX = canvas.getWidth() / 2;
int centerY = canvas.getHeight() / 2;
float stretch = stretchFade;
int sum = RenderUtils.sum(data);
p.setColor((p.getColor() + sum / 2)); //change color of circle
if (sum > BOOST_TRASH_HOLD) {//prominent beat
stretch = (float) Math.min(canvas.getWidth(), canvas.getHeight()) / Byte.MAX_VALUE / 3; //maximum
stretchFade = stretch;
}
double radDif = 2 * Math.PI / data.length; //the angle between each element of the array
double radPos = 0;
float lX = (float) Math.cos(radPos) * data[0] + centerX;
float lY = (float) Math.sin(radPos) * data[0] + centerY;
float cX;
float cY;
for (byte b : data) {
cX = (float) Math.cos(radPos) * b * stretch + centerX;
cY = (float) Math.sin(radPos) * b * stretch + centerY;//calculate position of outline, stretch indicates promince of the beat
canvas.drawLine(lX, lY, cX, cY, p);
lX = cX;
lY = cY;
radPos += radDif;
}
stretchFade = Math.max(1, stretchFade / 1.2f);//beat fades out
}
}
You can programm your own renderes and let the user select which one he wants to use. Just pass the array from onWaveformDataCapture to the onRender method.
Utils for analysing the waveform (the amplitude is stored kind of weird):
class RenderUtils {
private static final byte SHIFT = Byte.MAX_VALUE;
static int sum(byte[] data) {
int sum = 0;
for (byte b : data)
sum += b;
return sum;
}
static int toAmplitude(byte b) {
return b > 0 ? b + SHIFT : -b;//+127=high positive;+1=low positive;-127=low negative;-1=high negative
}
static float toAmplitude(float f) {
return f > 0 ? f + SHIFT : -f;//+127=high positive;+1=low positive;-127=low negative;-1=high negative
}
}
Hello I searched in the forum,but coudn't find a helpful answer.
I'm making a game with AndEngine and I'm stuck for 3 days on shooting from rotating sprite.
That is my code and how I rotate the gun.I tried here to shoot a bullet ,but it shoots from a wrong starting point I would want to shoot a bullet from the end of the gun.
#Override
public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
if(pSceneTouchEvent.isActionMove()){
final float dX = pSceneTouchEvent.getX() - machine.getX();
final float dY = pSceneTouchEvent.getY() - machine.getY();
float angle = (float) Math.atan2(dX,dY);
float rotation = MathUtils.radToDeg(angle) + 1;
machine.setRotation(rotation - 90);
Log.d("BUG",machine.getRotation() + "");
if(machine.getRotation() >= 84 ){
machine.setRotation(84);
}
if(machine.getRotation() <= -54 ){
machine.setRotation(-54);
}
final int incrementXValue = 15;
long sElapsed = System.currentTimeMillis() - lastFire;
if(bulletsAmout > 0 && sElapsed > cooldownBetweenShoot * cdModd){
e = new Entity(0,machine.getY());
e.setRotation(getRotation());
SceneManager.getInstance().getCurrentScene().attachChild(e);
float x2 = (float) (machine.getSceneCenterCoordinates()[0] + machine.getWidth() /2 * Math.cos(machine.getRotation()));
float y2 = (float) (machine.getSceneCenterCoordinates()[1] + machine.getWidth() /2 * Math.sin(machine.getRotation()));
float realX = (float) (Math.toRadians(x2) + machine.getWidth());
realY = (float) Math.toRadians(y2);
bullets = new Sprite(realX,realY, resourcesManager.bulletRegion.deepCopy(), vbom){
protected void onManagedUpdate(float pSecondsElapsed) {
float currentX = this.getX();
this.setX(currentX + incrementXValue);
super.onManagedUpdate(pSecondsElapsed);
}
};
bullets.setScale(0.06f);
e.attachChild(bullets);
projectilesToBeAdded.add(bullets);
bulletsAmout--;
lastFire = System.currentTimeMillis();
setBulletsText(bulletsAmout);
resourcesManager.pistolSound.play();
}
return true;
}
return false;
}
Assuming you are using GLES2-AnchorCenter:
You can position the bullet by setting it to the position of the end of the gun that you can get by calling gun.convertLocalToSceneCoordinates(gunMuzzleX, gunMuzzleY).
Then set the bullets rotation to the rotation of the gun.
apply velocity to the bullet. Calculate the speed-vector as follows FloatMath.sin(rotationOfBulletInRadians) * speed and FloatMath.cos(rotationOfBulletInRadians) * speed.
Be aware that you have to pass the rotation in radians to the sin and cos function NOT in degrees!
So I found how to fix that.
The problem is in this line of code :
e = new Entity(0,machine.getY());
Should be :
e = new Entity(machine.getX() - (machine.getHeight() / 2),machine.getY())
There is no much time delay or gap between random targets fall that is there is a continous move of targets in my cocos2d-android game app, googled alot but could not get any, please help me guys
below code is used for target.
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 minX = (int)(target.getContentSize().width / 2.0f);
int maxX = (int)(winSize.width - target.getContentSize().width / 2.0f);
int rangeX = maxX - minX;
int actualX = rand.nextInt(rangeX) + minX;
// Create the target slightly off-screen along the right edge,
// and along a random position along the Y axis as calculated above
// target.setPosition(getContentSize().width + (target.getContentSize().width / 2.0f), actualX);
target.setPosition(actualX, winSize.height + target.getContentSize().height);
addChild(target);
target.setTag(1);
_targets.add(target);
// Determine speed of the target
int minDuration = 20;
int maxDuration = 30;
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, actualX));
CCMoveTo actionMove = CCMoveTo.action(actualDuration, CGPoint.ccp(actualX, - target.getContentSize().height));
CCCallFuncN actionMoveDone = CCCallFuncN.action(this, "spriteMoveFinished");
CCSequence actions = CCSequence.actions(actionMove, actionMoveDone);
target.runAction(actions);
}
this.schedule("Method_name", 6.0f);
This thing make the delay b/w the two sprite. You can change the float value according to u and make this change in the constructor of your Game class.
Ok, this should be simple enough, but I'm tripping myself up on the math. Using AndEngine BTW>
I'm using some of the tutorials out there... hero on the left of the screen (landscape) shooting right. Everything works wonderfully. Now I'd like to have the hero on the right side of the screen shooting left. I'm going in circles and would great appreciate some help. Here is the code I'm using for left hero, shooting right.
/** shoots a projectile from the player's position along the touched area */
private void shootProjectile(final float pX, final float pY) {
int offX = (int) (pX - (hero.getX()));
int offY = (int) (pY - (hero.getY() + hero.getHeight()/2));
if (offX <= 0) return;
// position the projectile on the player and set up path
projectile = pPool.obtainPoolItem();
int realX = (int) (mCamera.getWidth() - (hero.getX() ) );
float ratio = (float) realX / (float) offX;
int realY = (int) ((offY * ratio));
float length = (float) Math.sqrt((realX * realX) + (realY * realY));
float velocity = 280.0f / .5f; // 480 pixels per (sec)f on screen
float realMoveDuration = length / velocity;
// defining a moveBymodifier from the projectile's position to the
// calculated one
//this code angles the projectile sprite
double PI = 3.14159265;
float dx = pX - hero.getX();
float dy = pY - hero.getY()-50;
double Radius = Math.atan2(dy,dx);
double Angle = Radius * 180 / PI;
projectile.setRotation((float)Angle); // sets the angle of the projectile
//Move modifier for projectile
MoveByModifier movMByod = new MoveByModifier(realMoveDuration, realX, realY);
final ParallelEntityModifier par = new ParallelEntityModifier(movMByod);
DelayModifier dMod = new DelayModifier(0.001f);
dMod.addModifierListener(new IModifierListener<IEntity>() {
#Override
public void onModifierStarted(IModifier<IEntity> arg0, IEntity arg1) {
}
#Override
public void onModifierFinished(IModifier<IEntity> arg0, IEntity arg1) {
// TODO Auto-generated method stub
shootingSound.play();
projectile.setVisible(true);
projectile.setPosition(hero.getX(), hero.getY() + hero.getHeight() / 2);
projectilesToBeAdded.add(projectile);
projectile.animate(50);
}
});
SequenceEntityModifier seq = new SequenceEntityModifier(dMod, par);
projectile.registerEntityModifier(seq);
projectile.setVisible(false);
mMainScene.attachChild(projectile, 1);
I've got the hero positioned fine on the right side. What do I need to do to get the projectile to move to the left correctly?
Thanks a ton for any help.
MWM
You shouldn't use DelayModifier the way you do. Instead create a PhysicsHandler for your sprites and then set velocity to the PhysicsHandler. Something like:
PhysicsHandler phys = new PhysicsHandler();
projectile.registerUpdateHandler(phys);
phys.setVelocityX(50);
and this will take care of moving your projectile. You can also set acceleration on the physics handler the same way. So if you set the initial velocity to point up and left and then set the acceleration pointing down, the projectile will first fly left and up and then gradually fall down. And you don't have to do any calculations yourself.
This code looks like the one from http://jimmaru.wordpress.com/2011/09/28/andengine-simple-android-game-tutorial/
if it is, try this:
private void shootProjectile(final float pX, final float pY) {
int side = 1;
int offX = (int) (pX - (hero.getX()));
int offY = (int) (pY - (hero.getY() + hero.getHeight()/2));
if (offX <= 0){
side=-1
}
// position the projectile on the player and set up path
projectile = pPool.obtainPoolItem();
int realX = (int) (mCamera.getWidth() - (hero.getX() ) ) * side;
....
I got the same problem with the code from link, with this change i could shoot fot both sides with a player in the middle of screen.