Libgdx: how to detect if an enemy was touched? - java

I want to add to the score of my game +1 when an enemy was touched, I tried two methods addListener and touchDown but not worked for me or I didn't use them right.
How can I do that my (enemy object is linked to an userData and Actor classes, I regroup many different sizes for my enemy in an enum class also those enemies move from the top of the screen to bot. How to detect if an enemy was touched?
public class GameStage extends Stage {
// This will be our viewport measurements while working with the debug renderer
private static final int VIEWPORT_WIDTH = 13;
private static final int VIEWPORT_HEIGHT = 20;
private World world;
private Ground ground;
private Enemy enemy;
private final float TIME_STEP = 1 / 300f;
private float accumulator = 0f;
private Rectangle bounds;
private Vector3 touchPoint = new Vector3();;
private int score;
private String yourScoreName;
BitmapFont yourBitmapFontName;
private SpriteBatch batch;
private OrthographicCamera camera;
private Box2DDebugRenderer renderer;
public GameStage() {
world = WorldUtils.createWorld();
renderer = new Box2DDebugRenderer();
Gdx.input.setInputProcessor(this);
batch = new SpriteBatch();
score = 0;
yourScoreName = "score: 0";
yourBitmapFontName = new BitmapFont();
setUpWorld();
setUpCamera();
}
public void setUpWorld(){
world = WorldUtils.createWorld();
setUpGround();
createEnemy();
}
private void setUpGround(){
ground = new Ground (WorldUtils.createGround(world));
addActor(ground);
}
private void createEnemy() {
enemy = new Enemy(WorldUtils.createEnemy(world));
// (1) *****using addListener method
enemy.addListener(new InputListener()
{
#Override
public boolean touchDown(InputEvent event, float x, float y,
int pointer, int button)
{
score++;
yourScoreName = "score: " + score;
return true;
}
});
/*enemy.addListener(new ClickListener() {
public void clicked() {
world.destroyBody(enemy.getBody());
}});*/
//bounds = new Rectangle(enemy.getX(), enemy.getY(), enemy.getWidth(), enemy.getHeight());
addActor(enemy);
}
private void setUpCamera() {
camera = new OrthographicCamera(VIEWPORT_WIDTH, VIEWPORT_HEIGHT);
camera.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2, 0f);
camera.update();
}
#Override
public void act(float delta) {
super.act(delta);
checkEnemy();
// Fixed timestep
accumulator += delta;
while (accumulator >= delta) {
world.step(TIME_STEP, 6, 2);
accumulator -= TIME_STEP;
}
//TODO: Implement interpolation
}
private void checkEnemy(){
final Body body = enemy.getBody();
UserData userData = enemy.getUserData();
bounds = new Rectangle(enemy.getBody().getPosition().x, enemy.getBody().getPosition().y, enemy.getUserData().getWidth(), enemy.getUserData().getHeight());
// bounds = new Rectangle(body.getPosition().x, body.getPosition().y,userData.getWidth() ,userData.getHeight());
if (!BodyUtils.enemyInBounds(body,userData)){
world.destroyBody(body);
createEnemy();}
}
public World getWorld(){
return world;
}
// (2) ****using TouchDown method
#Override
public boolean touchDown(int x, int y, int pointer, int button) {
// Need to get the actual coordinates
translateScreenToWorldCoordinates(x, y);
// score++;
// yourScoreName = "score: " + score;
if(enemyTouched(touchPoint.x,touchPoint.y)){
// world.destroyBody(enemy.getBody());
score++;
yourScoreName = "score: " + score;
}
return super.touchDown(x, y, pointer, button);
}
private boolean enemyTouched(float x, float y) {
return bounds.contains(x, y);
}
private void translateScreenToWorldCoordinates(int x, int y) {
getCamera().unproject(touchPoint.set(x, y, 0));
}
#Override
public void draw() {
super.draw();
batch.begin();
yourBitmapFontName.setColor(1.0f, 1.0f, 1.0f, 1.0f);
yourBitmapFontName.draw(batch, yourScoreName, 25, 100);
batch.end();
enemy.setBounds(enemy.getBody().getPosition().x,enemy.getBody().getPosition().y,enemy.getUserData().getWidth(),enemy.getUserData().getHeight());
renderer.render(world, camera.combined);
}
}
A screen from my game:

It should work the way you did it (with the addListener() method). But you have to set the correct bounds of the actor (width, height, position): actor.setBounds(x, y, width, height). I would use the body to get these values. You can also use a ClickListener instead of the InputListener.

Related

Libgdx Input don't working on Android

I'm new in Libgdx and I'm trying to make a map that can be explored using Camera. Fo that I implements GestureListener in my own Map class.
public class Map extends Stage implements GestureListener {
public String mapName;
private Sprite background;
public LocationPoint points[];
private OrthographicCamera camera;
private Batch batch;
public Music anbientSound;
public int numOfPoints;
public int locationsX[];
public int locationsY[];
public Map(Sprite background) {
this.background = background;
}
public Sprite getBackground() {
return background;
}
public void activate() {
InputMultiplexer inputChain = new InputMultiplexer();
if(points==null) {
points = new LocationPoint[numOfPoints];
for(int i = 0; i < numOfPoints; i++) {
points[i] = new LocationPoint(locationsX[i], locationsY[i]);
addActor(points[i]);
}
}
batch = GameUtils.batch;
camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
camera.position.set(camera.viewportWidth/2, camera.viewportHeight/2, 0);
camera.update();
Music music = GameUtils.addMusic(anbientSound);
music.setLooping(true);
music.play();
inputChain.addProcessor(this);
inputChain.addProcessor(new GestureDetector(this));
Gdx.input.setInputProcessor(inputChain);
}
public void draw() {
Gdx.gl20.glClearColor(0, 0, 0, 1);
Gdx.gl20.glClear(Gdx.gl20.GL_COLOR_BUFFER_BIT);
Batch batch = this.batch;
batch.setProjectionMatrix(camera.combined);
batch.begin();
background.draw(batch);
batch.end();
batch.begin();
for(int i = 0; i < numOfPoints; i++) {
points[i].draw(batch, 1);
addActor(points[i]);
}
batch.end();
}
public void dispose() {
GameUtils.stopMusic();
background.getTexture().dispose();
anbientSound.dispose();
}
#Override
public boolean pan(float x, float y, float deltaX, float deltaY) {
camera.translate(-deltaX, deltaY);
float initialX = camera.viewportWidth / 2;
float initialY = camera.viewportHeight / 2;
GameUtils.limitBound(camera, initialX, initialY, background.getWidth(), background.getHeight());
camera.update();
return true;
}
#Override
public boolean touchDown(float x, float y, int pointer, int button) {
return false;
}
#Override
public boolean tap(float x, float y, int count, int button) {
return false;
}
#Override
public boolean longPress(float x, float y) {
return false;
}
#Override
public boolean fling(float velocityX, float velocityY, int button) {
return false;
}
#Override
public boolean panStop(float x, float y, int pointer, int button) {
return false;
}
#Override
public boolean zoom(float initialDistance, float distance) {
return false;
}
#Override
public boolean pinch(Vector2 initialPointer1, Vector2 initialPointer2,
Vector2 pointer1, Vector2 pointer2) {
return false;
}
#Override
public void pinchStop() {}
}
The method activate() is used to activate the resources of the Map class. The class Map also have a ImageButtons called LocationPoints.
public class LocationPoint extends ImageButton {
private Monster monster;
private Trap trap;
public boolean occuped;
public boolean isTrap;
public int f = 20;
public int k = 20;
public LocationPoint(float x, float y) {
super(GameUtils.getLocationDrawable());
this.setSize(46, 46);
setPosition(x, y);
addListener(new InputListener(){
#Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
setPosition(f, k);
f += 10;
k += 10;
return super.touchDown(event, x, y, pointer, button);
}
});
}
public void occup(Monster monster) {
this.monster = monster;
occuped = true;
if(isTrap)
captured();
}
#Override
public void draw(Batch batch, float parentAlpha) {
super.draw(batch, parentAlpha);
}
public void empty() {
monster = null;
occuped = false;
}
public void captured() {
monster.capture();
}
public Monster getMonster() {
return monster;
}
}
In LocationPoint class I add a InputListener to make a thing when that LocationPoint is touched.
When a play the game on android both LocationPoints event and the Map pan event. But after I move the camera, when I touch on LocationPoint it don't fires that point event.
But when I return the camera to initial position the LocationPoints events works fine! Can you help me? (And sorry for my broken english...)
Actor is already a child so remove redundant call from draw() method.
for(int i = 0; i < numOfPoints; i++) {
points[i].draw(batch, 1);
addActor(points[i]); // <-- Not Should be in draw() call
}
Stage having own SpriteBatch that created by default constructor, use that one or pass own batch in Stage constructor.
Use getBatch() method of Stage if you want to draw something by yourself.
Creating camera in Map class also redundant, use getViewport().getCamera() that return camera of stage, you can typecast to OrthographicCamera
call super.dispose(); inside your dispose() method
Drawing all your Actor by yourself ? If you're not doing something beyond the scope, no need to override draw() method of Stage.

Java libGDX Game - Animation doesn't flip

I have a animation which i want to flip to the left if key LEFT is pressed, but it doesnt stay flipped. It only flips like 1 frame then turns back again.
Here is my GameScreen where i draw everything:
public class GameScreen extends ScreenManager{
//For the view of the game and the rendering
private SpriteBatch batch;
private OrthographicCamera cam;
//DEBUG
private Box2DDebugRenderer b2dr;
//World, Player and so on
private GameWorld world;
private Player player;
private Ground ground;
//player animations
private TextureRegion currFrame;
public static float w, h;
public GameScreen(Game game) {
super(game);
//vars
w = Gdx.graphics.getWidth();
h = Gdx.graphics.getHeight();
//view and rendering
batch = new SpriteBatch();
cam = new OrthographicCamera();
cam.setToOrtho(false, w/2, h/2);
//debug
b2dr = new Box2DDebugRenderer();
//world, bodies ...
world = new GameWorld();
player = new Player(world);
ground = new Ground(world);
}
#Override
public void pause() {
}
#Override
public void show() {
}
#Override
public void render(float delta) {
//clearing the screen
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
//updating
update(Gdx.graphics.getDeltaTime());
player.stateTime += Gdx.graphics.getDeltaTime();
//render
batch.setProjectionMatrix(cam.combined);
currFrame = Player.anim.getKeyFrame(Player.stateTime, true);
batch.begin();
batch.draw(currFrame, Player.body.getPosition().x * PPM - 64, Player.getBody().getPosition().y * PPM- 72);
batch.end();
//debug
b2dr.render(GameWorld.getWorld(), cam.combined.scl(PPM));
}
#Override
public void resize(int width, int height) {
}
#Override
public void hide() {
}
#Override
public void dispose() {
}
#Override
public void onKlick(float delta) {
}
public void update(float delta){
world.update(delta);
updateCam(delta);
Player.keyInput(delta);
System.out.println("X-POS" + Player.getBody().getPosition().x);
System.out.println("Y-POS" + Player.getBody().getPosition().y);
}
public void updateCam(float delta){
Vector3 pos = cam.position;
pos.x = Player.getBody().getPosition().x * PPM;
pos.y = Player.getBody().getPosition().y * PPM;
cam.position.set(pos);
cam.update();
}
}
and this is the Player class where the animation is:
public class Player {
public static Body body;
public static BodyDef def;
private FixtureDef fd;
//textures
public static Texture texture;
public static Sprite sprite;
public static TextureRegion[][] region;
public static TextureRegion[] idle;
public static Animation<TextureRegion> anim;
public static float stateTime;
//set form
private PolygonShape shape;
private GameScreen gs;
public Player(GameWorld world){
texture = new Texture(Gdx.files.internal("player/char_animation_standing.png"));
region = TextureRegion.split(texture, texture.getWidth() / 3, texture.getHeight() / 2);
idle = new TextureRegion[6];
int index = 0;
for(int i = 0; i < 2; i++){
for(int j = 0; j < 3; j++){
sprite = new Sprite(region[i][j]);
idle[index++] = sprite;
}
}
anim = new Animation<TextureRegion>(1 / 8f, idle);
stateTime = 0f;
def = new BodyDef();
def.fixedRotation = true;
def.position.set(gs.w / 4, gs.h / 4);
def.type = BodyType.DynamicBody;
body = world.getWorld().createBody(def);
shape = new PolygonShape();
shape.setAsBox(32 / 2 / PPM, 64/ 2 / PPM);
fd = new FixtureDef();
fd.shape = shape;
fd.density = 30;
body.createFixture(fd);
shape.dispose();
}
public static Body getBody() {
return body;
}
public static BodyDef getDef() {
return def;
}
public static Texture getTexture() {
return texture;
}
public static void keyInput(float delta){
int horizonForce = 0;
if(Gdx.input.isKeyJustPressed(Input.Keys.UP)){
body.applyLinearImpulse(0, 300f, body.getWorldCenter().x, body.getWorldCenter().y, true);
//body.applyForceToCenter(0, 1200f, true);
System.out.println("PRESSED");
}
if(Gdx.input.isKeyPressed(Input.Keys.LEFT)){
horizonForce -= 1;
sprite.flip(!sprite.isFlipX(), sprite.isFlipY());
}
if(Gdx.input.isKeyPressed(Input.Keys.RIGHT)){
horizonForce += 1;
}
body.setLinearVelocity(horizonForce * 20, body.getLinearVelocity().y);
}
}
thank you in advance and any answer is appreciated :D
Your sprite variable contain only one frame at the time of pressing left key. So, it flip that current sprite of your animation frame.
To solve the Problem you have to flip all the animation frame on pressing the left key.
You're only flipping last frame of Animation by sprite reference, You need to flip all frames of your Animation anim. You can flip in this way :
if(keycode== Input.Keys.RIGHT) {
for (TextureRegion textureRegion:anim.getKeyFrames())
if(!textureRegion.isFlipX()) textureRegion.flip(true,false);
}
else if(keycode==Input.Keys.LEFT) {
for (TextureRegion textureRegion:anim.getKeyFrames())
if(textureRegion.isFlipX()) textureRegion.flip(true,false);
}

mirrored against x axis movement

I am trying to implement movement to a point, where mouse was clicked.
But I have a problem with mirrored behaviour agains X axis.
When I click on top -> it moves to the bottom, when I click on bottom -> it moves to the top.
Here is for example original position
I clicked on the screen in position with red cross.
But it moves down (as arrow showed).
What's the problem? It seems something with movement vector I presume.
public class Player {
private static final float PLAYER_CIRCLE_RADIUS = 24f;
private static final float MOVEMENT_SPEED = 200f;
private final Circle playerCircle;
private Vector2 direction = new Vector2();
private Vector2 position;
private Vector2 velocity = new Vector2();
private Vector2 movement = new Vector2();
private Vector2 mouseClick = new Vector2();
public Player(float x, float y) {
position = new Vector2(x, y);
playerCircle = new Circle(x, y, PLAYER_CIRCLE_RADIUS);
}
public void draw(ShapeRenderer shapeRenderer) {
shapeRenderer.circle(position.x, position.y, playerCircle.radius);
}
public void update(float delta) {
movement.set(velocity).scl(delta);
if (position.dst2(mouseClick) > movement.len2()) { position.add(movement); }
else { position.set(mouseClick); }
}
public void setDirection(float x, float y) {
mouseClick.set(x, y);
direction.set(mouseClick).sub(position).nor();
velocity.set(direction).scl(MOVEMENT_SPEED);
}
public Vector2 getDirection() {
return direction;
}
public Circle getPlayerCircle() {
return playerCircle;
}
public Vector2 getMouseClick() {
return mouseClick;
}
}
public class GameScreen extends ScreenAdapter {
private static final float WORLD_WIDTH = 640;
private static final float WORLD_HEIGHT = 480;
private ShapeRenderer shapeRenderer;
private Viewport viewport;
private Camera camera;
private Player player;
private Destination dest;
#Override
public void render(float delta) {
clearScreen();
update(delta);
shapeRenderer.setProjectionMatrix(camera.projection);
shapeRenderer.setTransformMatrix(camera.view);
shapeRenderer.begin(ShapeRenderer.ShapeType.Line);
dest.draw(shapeRenderer);
player.draw(shapeRenderer);
shapeRenderer.end();
}
#Override
public void resize(int width, int height) {
viewport.update(width, height);
}
#Override
public void show() {
camera = new OrthographicCamera();
camera.position.set(WORLD_WIDTH / 2, WORLD_HEIGHT / 2, 0);
viewport = new FitViewport(WORLD_WIDTH, WORLD_HEIGHT, camera);
shapeRenderer = new ShapeRenderer();
player = new Player(WORLD_WIDTH / 2, WORLD_HEIGHT / 2);
dest = new Destination();
Gdx.input.setInputProcessor(new InputAdapter() {
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
dest.setPosition(screenX, screenY);
camera.unproject(new Vector3(screenX, screenY, 0));
player.setDirection(screenX, screenY);
return true;
}
});
}
private void clearScreen() {
Gdx.gl.glClearColor(Color.BLACK.r, Color.BLACK.g, Color.BLACK.b, Color.BLACK.a);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}
private void update(float delta) {
player.update(delta);
}
}
What you describe is actually mirrored on the Y-Axis.
The reason for this behaviour is most likely that your drawing matrix is set in such a way that the origin is in the bottom-left corner with the Y-Axis pointing up, but gui's have their origin at the top-left corner with the Y-Axis pointing down. So when you get your mouse position you should do something like:
actualPosY = screenHeight - mousePosY
This effectively transforms your mouse position to your drawing space.

Libgdx sceene2d and Input Processor not updating screen

I am rather new to the libgdx Framework so I hope I am not asking anything stupid, but I have a problem with updating my screen on the toucheEvent. It seems that the touch event fires, but the stage is not updated so the screen is all the time the same. Here is the code
MainClass
public class MainGame implements Screen {
public LabirintGame game;
public Stage stage;
public OrthographicCamera camera;
public ActorM rigth;
public ActorM wrong;
public MainGame(LabirintGame game) {
this.game = game;
this.camera = new OrthographicCamera();
}
#Override
public void show() {
this.camera.setToOrtho(false, 800, 480);
stage = new Stage(new ScreenViewport());
stage.clear();
Words group = new Words(stage);
InputMultiplexer inputMultiplexer = new InputMultiplexer();
inputMultiplexer.addProcessor(stage);
inputMultiplexer.addProcessor(new MyInputProcessor(stage, camera));
Gdx.input.setInputProcessor(inputMultiplexer);
//Add wrong and rigth boxes
rigth = new ActorM("box", 0, 0, 200,200);
wrong = new ActorM("box",(game.width - 230), 0, 200, 200);
wrong.moveBy(200,200);
Button createButtons = new Button();
createButtons.setStyle("atlas-besede/besede.atlas", "buttonOff", "buttonOn");
TextButton ValidationButton = createButtons.createButton("Validate", (game.width/2), 0, 150, 150);
ValidationButton.addListener(new InputListener() {
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
game.setScreen(new Labirint(game));
return true;
}
});
stage.addActor(ValidationButton);
stage.addActor(rigth);
stage.addActor(wrong);
List<String> backgrounds = Arrays.asList("s", "z");
for (int i = 0; i < backgrounds.size(); i++) {
Word actor = new Word(backgrounds.get(i),(i + 1) * 300, 300, 100, 100);
actor.setPosition((i + 1) * 300, 300);
actor.setName(backgrounds.get(i));
group.addActor(actor);
}
stage.addActor(group);
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
game.batch.begin();
game.batch.setProjectionMatrix(camera.combined);
game.batch.end();
}
ActorM
package com.mygdx.game;
public class ActorM extends Actor {
public SpriteBatch batch;
public TextureAtlas atlas;
public TextureAtlas.AtlasRegion region;
Sprite sprite;
public int x;
public int y;
public int width;
public int height;
public ActorM(String actorName, int x, int y, int width, int height) {
//this.region = region;
super();
batch = new SpriteBatch();
atlas = new TextureAtlas(Gdx.files.internal("atlas-start/atlas-start.atlas"));
sprite = atlas.createSprite(actorName);
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.setBounds(0, 0, sprite.getWidth(), sprite.getHeight());
setTouchable(Touchable.disabled);
setName(actorName);
setPosition(x,y);
}
#Override
public void draw (Batch batch, float parentAlpha) {
batch.draw(sprite, x,y, width, height);
}
public void move(int posX){
this.x = this.x + posX;
}
}
MyInputProcessor
public class MyInputProcessor implements InputProcessor {
private OrthographicCamera camera;
private Stage stage;
private Vector2 coordinates;
private Music sound;
public MyInputProcessor( Stage stage, OrthographicCamera camera) {
this.stage = stage;
this.camera = camera;
}
#Override
public boolean keyDown(int keycode) {
return false;
}
#Override
public boolean keyUp(int keycode) {
return false;
}
#Override
public boolean keyTyped(char character) {
return false;
}
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button)
{
//Gdx.app.log("", "x " + screenX + " y " + screen`enter code here`Y + " pointer " + pointer);
Vector2 coordinates = stage.screenToStageCoordinates(new Vector2((float)screenX,(float)screenY));
Actor hitactor = stage.hit(coordinates.x, coordinates.y, true);
Gdx.app.log("", coordinates.toString());
if (hitactor != null){
//Gdx.app.log("", "HIT" + hitactor.getName());
Gdx.app.log("", "HIT" + hitactor.getRotation());
hitactor.setRotation(hitactor.getRotation() + 1f);
hitactor.setPosition(5,5);
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}
return true;
}
#Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
return false;
}
#Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
coordinates = stage.screenToStageCoordinates(new Vector2((float)screenX,(float)screenY));
Actor hitactor = stage.hit(coordinates.x, coordinates.y, true);
if (hitactor != null){
Gdx.app.log("", "Drag");
hitactor.setRotation(hitactor.getRotation() + 1f);
}
camera.update();
return true;
}
#Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
#Override
public boolean scrolled(int amount) {
return false;
}
}
Your "ValidationButton" uses an InputProcessor that always returns true and it's the first actor in the stage, so nothing else in the stage will ever get an opportunity to respond to touch down events. Furthermore, since your stage is the first input processor in your InputMultiplexer, your other input processor never gets an opportunity to respond to touch down events either.
You should use an EventListener on your button instead of an InputListener, so much of the logic will be taken care of for you.
By the way, your ActorM class is spawning a SpriteBatch that it never uses. SpriteBatch takes up significant memory, and there's no need for there to be more than one of them in your game. The Stage already has a reference to a SpriteBatch that it passes into your Actor's draw method, so the Actor does not need to create or even reference a SpriteBatch.
Also, your ActorM class is loading a complete copy of a TextureAtlas for itself so there will be duplicate Textures loaded for each instance of ActorM, and you lose all the benefits of a TextureAtlas, since you won't be using it for sprite batching. You need to load the TextureAtlas only one time, and pass a reference of it into the constructor of your ActorM class, so they can all share the same Texture.

Random Level Generation with LibGDX

I have made a class for the level generation and have got so far with it:
public class LevelGenerator {
private Sprite environment;
private float leftEdge, rightEdge, minGap, maxGap, y;
public Enemy enemy;
public LevelGenerator(Sprite environment, float leftEdge, float rightEdge,
float minGap, float maxGap) {
this.environment = environment;
this.leftEdge = leftEdge;
this.rightEdge = rightEdge;
this.minGap = minGap;
this.maxGap = maxGap;
}
public void generate(float topEdge){
if(y + MathUtils.random(minGap, maxGap) < topEdge)
return;
y = topEdge;
float x = MathUtils.random(leftEdge, rightEdge);
}
Basically, what I want to happen is for the enemy block to randomly generate on the sides of the screen. Here is the enemy block class (very simple):
public class Enemy extends Sprite{
public Enemy(Sprite sprite) {
super(sprite);
}
#Override
public void draw(Batch spriteBatch){
super.draw(spriteBatch);
}
}
This is what the game looks like at the moment when the block is just simply drawn on the game screen in a static position: http://i.imgur.com/SIt18Qn.png. What I am trying to achieve is for these "enemy" blocks to spawn randomly on either side of the screen but I can't seem to figure out a way to do it with the code I have so far.
Thank you!
I could not test but I think it will be fine, you have a rectangle if you want to see if it collides with another actor, if so updates its position in the update and draw method, and ramdon method start customizing to see if the coordinates, which colicionan be assigned to another actor rectagulo enemy or bye.
public class overFlowEnemy extends Sprite {
private final float maxH = Gdx.graphics.getHeight();
private final float maxW = Gdx.graphics.getWidth();
private Rectangle rectangle;
private Random random = new Random();
private float inttt = 0;
private float randomN = 0;
private boolean hasCollided = false;
public overFlowEnemy(Sprite sprite) {
super(sprite);
crearEnemigo();
rectangle = new Rectangle(getX(), getY(), getWidth(), getHeight());
}
#Override
public void draw(Batch spriteBatch) {
super.draw(spriteBatch);
}
private void crearEnemigo(){
setX(RandomNumber((int)maxW));
setY(RandomNumber((int)maxH));
}
private int RandomNumber(int pos) {
random.setSeed(System.nanoTime() * (long) inttt);
this.randomN = random.nextInt(pos);
inttt += randomN;
return (int)randomN;
}
public Rectangle getColliderActor(){
return this.rectangle;
}
}
the class as this should create a random enemy.
Edit: rereading your question, is that my English is not very good, and I think you wanted to be drawn only on the sides of the screen if so, tell me or adapts the class because when you create thought, which was across the screen.
I just added another class, if you can and want to work as you tell me which is correct, and delete the other.
public class overFlow extends Sprite {
private final float maxH = Gdx.graphics.getHeight();
private final float maxW = Gdx.graphics.getWidth();
private Rectangle rectangle;
private Random random = new Random();
private float inttt = 0;
private float randomN = 0;
private boolean hasCollided = false;
public overFlow(Sprite sprite) {
super(sprite);
crearEnemigo();
rectangle = new Rectangle(getX(), getY(), getWidth(), getHeight());
}
#Override
public void draw(Batch spriteBatch) {
super.draw(spriteBatch);
}
private void crearEnemigo(){
setX(RandomNumber((int)maxW, true));
setY(RandomNumber((int)maxH, false));
}
private int RandomNumber(int pos, boolean w) {
random.setSeed(System.nanoTime() * (long) inttt);
if (w = true){
this.randomN = random.nextInt((pos));
if(randomN % 2 == 0){
randomN = (pos - getWidth());
}else{
randomN = 0; //left screen
}
}else{
this.randomN = random.nextInt(pos - (int)getHeight());
}
inttt += randomN;
return (int)randomN;
}
public Rectangle getColliderActor(){
return this.rectangle;
}
}

Categories