How to make set sprite position based on degree? - java

I have a sprite arrow that rotates like a clock hand, I need my other sprite to spawn where the arrow is pointed.
//arrow rotation:
int x=Gdx.input.getX();
int y=Gdx.graphics.getHeight()-Gdx.input.getY();
double radians= Math.atan2(y - launcherSpr.getY(), x - arrowSpr.getX());
float angle=(float)radians*MathUtils.radiansToDegrees-85;
arrowSpr.setRotation(angle);
//The other sprite that is spawned whenever the method is called
public void newBullet(){
Sprite sprite=Pools.obtain(Sprite.class);
sprite.set(bulletSpr);
sprite.setPosition(300, 600);
bullets.add(sprite);
}
Right now when the method newBullet() is called, a bullet sprite will spawn and it's Y is translated by 5(going upward by 5 pixels per frame). What I want is that the bullet will spawn based on where the arrow is pointed and go upward or downward based on the situation.

Related

Translate transition not working right on keypress

I'm trying to make a ball bounce up and down with the use of translate transition. I'm first trying to make the ball move up before it starts moving down. the code I used for moving it up is like this
public void moveUp(Circle player){
TranslateTransition goUp = new TranslateTransition(Duration.millis(500),player);
goUp.setByY(-20);
goUp.play();
}
and I'm updating the value of the ball(player) on every keypress as follows(p.s player is of type Circle)
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent keyEvent) {
if(keyEvent.getCode() == KeyCode.SPACE){
moveUp(player);
player.setCenterY(player.getCenterY-20);
}
}
});
the only problem is that the amount the ball moves is not the same as the amount I'm updating. Taking a few values as example(Take note that the player's original center was 400,300) I got 280 as the updated value of the player's centerY, yet the centreY of the ball on screen was at around the 260 which is far off. How do I fix this so that the player's centreY gets shifted by the same amount it moves on screen?
This is because the Circle (player) has a translateY property in addition to its centerY property as mentioned by #James_D. translateY is a property common to all nodes. Whenever a TranslateTransition is applied, the coordinates of the Node (player in this case) do not change. Instead its 'local origin' changes.
Circle player = new Circle(10);
TranslateTransition goUp = new TranslateTransition(Duration.millis(500),player);
goUp.setByY(-20);
goUp.play();
When this code is executed the origin for the player moves up by 20 pixels, and the centerY property stays the same. If the coordinates were originally (400,300), they stay the same, but are now referenced with respect to the new local origin.
This procedure of modifying the coordinate axes themselves, is common for all transformations as explained in the javadoc for Node.
A translation transformation is one which shifts the origin of the node's coordinate space along either the x or y axis.
Note that as with all transformations, the x, y, width, and height variables of the rectangle (which remain relative to the local coordinate space) have not changed, but rather the transformation alters the entire coordinate space of the rectangle.
If you want to change the centerY property instead of the translateY property, you can use the Timeline class instead of TranslateTransition. You could refer this SO answer for using the Timeline class for this purpose.

How to make an object move on any direction?

I have a gun sprite that rotates 360 degrees,I wan't it to fire bullets on any direction, how do I do that? I can't just increment the x,y coordinates of the bullet cause it will just go up,down,left and right.
EDIT:
The bullet movement seems only to rotate but not going anywhere or outside the screen
bulletPosition.x=MathUtils.cosDeg(cannonObj.cannonAngle())*2;
bulletPosition.y=MathUtils.sinDeg(cannonObj.cannonAngle())*2;
bulletVelocity.x=MathUtils.cosDeg(cannonObj.cannonAngle())*10;
bulletVelocity.y=MathUtils.sinDeg(cannonObj.cannonAngle())*10;
bulletPosition.x+=bulletVelocity.x*deltaTime;
bulletPosition.y+=bulletVelocity.y*deltaTime;
//spawning bullets
public void draw(SpriteBatch batch){
bulletIterator=bullets.iterator();
while(bulletIterator.hasNext()){
Sprite sprite=bulletIterator.next();
sprite.draw(batch);
sprite.setPosition(bulletPosition.x,bulletPosition.y);
}
Vector gunPos; // the gun position,dah
Vector bulletPos; //the bullet position
Vector bulletVelocity; //need explanation?
float gunAngle; //the rotation of the gun in degrees
float distanceFromCenter=gunSize.x/2; //the distance from the gun center you want the bullet to appear
bulletPos.x=MathUtils.cosDeg((gunAngle)) * distanceFromCenter;
bulletPos.y=MathUtils.cosDeg((gunAngle)) * distanceFromCenter;
bulletPos.plus(gunPos);
bulletVelocity.x=MathUtils.cosDeg((gunAngle)) * bulletSpeed;
bulletVelocity.y=MathUtils.cosDeg((gunAngle)) * bulletSpeed;

How to change Sprite texture to Animation

I have a Sprite that spawns every second, what I wan't to do is change the sprite texture to animation, and the when it's touched it will be back to a normal texture.
public void draw(SpriteBatch batch){
enemyIterator=enemies.iterator(); //arraylist iterator
boolean touched=Gdx.input.justTouched();
float touchX=Gdx.input.getX();
//rendering and making the current sprite move
while(enemyIterator.hasNext()){
Sprite sprite=enemyIterator.next();
sprite.draw(batch);
sprite.translateY(deltaTime*movement);
//detecting if the screen is touched and if the inputX is inside of the sprite.
if(touched==true && touchX > sprite.getX() && touchX < sprite.getX()+sprite.getWidth()){
enemyIterator.remove(); //removing the sprite when touched.
Pools.free(sprite); //freeing the Pools
}
}
To change from a texture to an animation
Create a subclas of Sprite called MySprite or something, and override the draw(batch) method.
In the overriden draw method, if you want to draw a texture, simply call super.draw(batch), otehrwise use your animation draw code. You can get the delta time using Gdx.graphics.getDeltaTime()
Why you have to specify timePassed
Your program will run at different frame rates to the animation, so by telling the animation how much time has passed, it can work out what frame it should be on according to it's own framerate.
Note that the framerate of your app can vary from frame-to-frame depending on how much work it has to do.

LibGDX problems rotating sprite

OK so I'm really confused I've rotated sprites before and had no problem such as rotating a boat as it moves through an ocean, but for some reason I'm having a really big problem this time. So I create a texture in an assets file, but not static textures. I load the texture using the following:
class Assets{
Texture img;
public Assets(){
img = new Texture(Gdx.files.internal("images/PNG.png")
And then I call the assets in the main class by calling:
Assets assets = new Assets()
And then I have a class that is an animator just for this main character because his animation is so different and varied from other characters.
class Animations{
Guy MYGUY;
Texture firstTexture;
ArrayList<Texture> running;
Sprite CurrentSprite;
public Animations(Texture standingStill, Guy myGuy){
MYGUY = myGuy;
firstTexture = standingStill;
running = new ArrayList<Texture>();
running.add(firstTexture);
CurrentSprite = new Sprite(firstTexture);
public void update (int direction, int state){
CurrentSprite.setPosition(MYGUY.X, MYGUY.Y)
// I have a switch here, but it does nothing yet because I haven't added in different actions for the character.
//However I do have a switch for direction, because that is important right now
switch(state){
case Guy.LEFT:
CurrentSprite.set rotation(180);
//yes there are more, but even rotating 180 won't work correctly
}
Then I have a renderer class to draw everything, i have the object MyGuy in an object for the world called myLand and I draw it with:
myLand.GUY.animation.CurrentSprite(batch);
So my problem arises on the rotation, whenever it rotates 180 degrees it seems to always rotate around the coordinates (0, 0) instead of the center of the sprite. So it usually ends up where I move like five to the right, but then if I try to go left it does double the distance backwards, but the camera position stays the same, and the guy usually disappears off the left or right side of the screen.
Try use rotate(...)method instead of setRotation(...).
With setOrigin(widthSprite\2, heightSprite\2)
That action rotate sprite itself.
Try
sprite.setOriginCenter();
This should help
Instead of rotating the sprite, just flip it with this single line:
CurrentSprite.flip(true, false);
the first boolean is X flip (that's what you want to set as true when going left) and the second is the Y flip.

Binding sprite movement to the camera or scene (AndEngine)

I am using DigitalOnScreenControl to Move Player Sprite.But the Problem is that My Player Sprite goes out of Emulator Screen.I want player sprite be restricted to move in particular bounds and also camera to focus on player sprite as and when my sprite moves on.
i am trying this code:
public Scene onLoadScene() {
// Auto-generated method stub
this.mEngine.registerUpdateHandler(new FPSLogger());
final Scene mScene=new Scene();
mScene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f));
final int centerX=(CAMERA_WIDTH-this.mPlayerTextureRegion.getWidth())/2;
final int centerY=(CAMERA_HEIGHT-this.mPlayerTextureRegion.getHeight())/2;
final Sprite player=new Sprite(centerX, centerY, this.mPlayerTextureRegion);
this.mCamera.setChaseEntity(player);
final PhysicsHandler physicsHandler=new PhysicsHandler(player);
player.registerUpdateHandler(physicsHandler);
mScene.attachChild(player);
this.mDigitalOnScreenControl=new DigitalOnScreenControl(0,CAMERA_HEIGHT-mOnScreenControlBaseTextureRegion.getHeight(),this.mCamera,this.mOnScreenControlBaseTextureRegion,this.mOnScreenControlKnobTextureRegion,0.1f,new IOnScreenControlListener() {
#Override
public void onControlChange(BaseOnScreenControl pBaseOnScreenControl,
float pValueX, float pValueY) {
// TODO Auto-generated method stub
physicsHandler.setVelocity(pValueX*100, pValueY*100);
}
});
this.mDigitalOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
this.mDigitalOnScreenControl.getControlBase().setAlpha(0.5f);
this.mDigitalOnScreenControl.getControlBase().setScaleCenter(0, 128);
this.mDigitalOnScreenControl.getControlBase().setScale(1.25f);
this.mDigitalOnScreenControl.getControlKnob().setScale(1.25f);
this.mDigitalOnScreenControl.refreshControlKnobPosition();
mScene.setChildScene(this.mDigitalOnScreenControl);
return mScene;
}
Honestly I am Very new in andEngine Development
please Help me With Heart
Thank in advance.
Binding the Player to the Camera
What you're asking for is a form of collision handling. Essentially, when you've moved the player outside of the scene, you want to move the player back into the scene, and you want to do that in the same update as you've moved the player, immediately after moving the player, so the out-of-scene location never gets rendered.
Lets take apart what I just said. You move the player here:
physicsHandler.setVelocity(pValueX*100, pValueY*100);
Moving the player with a physicsHandler is perfectly reasonable and takes into account variable frame-rate so, so far, good job. Now you want to move them back into the scene if they're outside it. So we're going to need a new method. Lets throw in a method call right after moving the player (we'll call it "adjustToSceneBinding()" so you have this:
physicsHandler.setVelocity(pValueX*100, pValueY*100);
adjustToSceneBinding(player);
Sidenote, I'd rather have this method be on the player (i.e., player.adjustToSceneBinding()), but your player object is just a sprite. I'd suggest you change that to a custom object that extends sprite so you can throw in your own code there. In any event, lets make the adjustToSceneBinding() method.
public boolean adjustToSceneBinding(Sprite player) {
// Correct the X Boundaries.
if (player.getX() < 0) {
player.setX(0);
} else if (player.getX() + player.getWidth() > CAMERA_WIDTH) {
player.setX(CAMERA_WIDTH - player.getWidth());
}
}
See what I did? If the player's X coordinate is less than zero, move them back to zero. If the player's X PLUS the player's width is more than the camera width, move them back to the camera width minus the player width. Don't forget the player X coordinate represents the left side of the sprite. That's why I'm taking into account the width in addition to the position for calculating the right side.
The above code only addresses left/right movement, but I'm going to let you extrapolate how to do the same for up down.
Binding the Player to the Map Size Instead
Now, what we did so far was really intended for the situation where the map "size" is no larger than the screen. But often what you'll want is a larger map than the screen size and a camera that chases the player around. To do that, just replace the code above, where I referred to the CAMERA_WIDTH with a number that represents the width of your "map". In other words, the map can be much larger than the camera. If you use larger numbers there (than, say, the width of the camera), and you set the camera to chase the player entity (as you have), then you'll have a map where the player can move around until they hit the bounds of the map.
Hope this helps! :)

Categories

Resources