I'm working on a breakout game for an assignment and for part 2 of it I need to include code that stops the bat from being moved out of the boundaries. I'm pretty sure that I need to use an if statements but I don't know what exactly I should put inside the brackets for else (something that will enable the bat to move). I
This is the code in particular I'm talking about.
if (dist < 0)
{
}
else
{} // move
if ((dist + 150)> 600)
{
}
else
{} // move
(Part 2 is in the ModelBreakout class).
There are lots of classes and just so many different parts of the code that are to do with the movement of the bat and I don't know what to use for this part, I would appreciate a hint of what I need to do!
Edit: I removed all of the classes because people were complaining. If you would like to view the classes go to this page and scroll down to the title Mini project: The BreakOut game.
Thanks for any help. I'm not looking for anyone to do my work for me, I would just like some guidance, I've worked out that I need to do an if statement, I'm just not sure of what I need to put inside it.
TL;DR.
I recently created a similar game. Here's how I implemented it.
Racket Class
protected static final float MIN_X = 10;
protected static final float MAX_X = 590;
public void moveLeft()
{
if (x > MIN_X)
{
x -= 5;
}
}
public void moveRight()
{
if (x < MAX_X)
{
x += 5;
}
}
Player extends Racket
public void process(int key)
{
if (key == KeyEvent.VK_KP_LEFT || key == KeyEvent.VK_LEFT)
{
moveLeft();
}
else if (key == KeyEvent.VK_KP_RIGHT || key == KeyEvent.VK_RIGHT)
{
moveRight();
}
}
Edit: This is not the complete classes. It's just some items lifted from them. There's a key listener added to the game which passes the key to Player.process().
Edit 2: Updated my code. Your width is set to 600 so the boundaries can be 10 and 590. This should work for you
Looking at the classes there are built in methods for each object on the screen, so you could do something like this:
If( Bat.GetX() < 0 ) {
Bat.moveX( *INSERT THE X HERE* )
}
And you also could do a the same thing for the max width. Also if you do a simple fix like this make sure to change the refresh rate of the screen, otherwise you will see the bat Jumping to the new position.
Related
So for a school project, I have to create a game with a program called 'Processing'.
I am creating a main menu with the switch statement. For that I want to use the buttons 'Start', 'Help', and 'exit'.i would like to use those buttons to change the variables of the switch statement. Therefore I'm using "mousePressed". The problem is that which button I'm pressing, is giving me the same result as the 'exit' button. Could somebody give me tips on how I can structure my menu better or even make my button work? I am using a library on Processing called 'ControlP5' to make my buttons.
here is my code so far:
int mode; // 1: intro screen, 2: game , 3: game over
final int INTRO = 1;
final int PLAY = 2;
final int GAMEOVER = 3;
//==============================================================
void setup(){
size(1920,1080);
mode = 1;
}
//========================================================
void draw(){
if(mode == 1){
introScreen();
}
else if (mode == 2){
gameItself();
}
else if (mode == 3){
gameOver();
}
else println("mode error");{
}
}
void introScreen(){
mode = 1;
static int Page = 0;
import controlP5.*;
ControlP5 cp5;
cp5= new ControlP5(this);
switch(Page){
case 0: // main menu
cp5.addButton("Start").setValue(0).setPosition(1420,250).setSize(400,100);
cp5.addButton("Exit").setValue(0).setPosition(1420,650).setSize(400,100);
cp5.addButton("Help").setValue(0).setPosition(1420,450).setSize(400,100);
break;
case 1: //help menu
cp5.addButton("Back").setValue(0).setPosition(1420,450).setSize(400,100);
break;
}
public void Start(){
if(mousePressed){
mode = 2; // switching to the game itself
}
println("Start");
}
public void Exit(){
if(mousePressed){
exit(); }
println("Exit");
}
public void Help(){
Page = 1;
println("Help");
}
public void Back(){
if(mousePressed){
Page = 0;
}
println("Back");
}
void gameItself(){
// game and stuff
}
void gameOver(){
//gameover
}
Take a look at how the mousePressed event works. You may use this information useful.
To achieve your goal as to change the Page variable by clicking buttons, there are multiple options. First, I'll go with the easier one, the one which doesn't need an import but just check for coordinates. Then I'll do the same thing, but with controlP5.
1. Just checking where the clicks lands
I'll go with the most basic one: detecting the "click" and checking if it's coordinates are inside a button.
First, we'll add the mouseClicked() method. This method is called every time a mouse button is pressed.
// I'm typing this out of IDE si there may be some quirks to fix in the code
void mouseClicked() {
switch(Page) {
case 0:
if (mouseX > 1420 && mouseX < 1420+400 && mouseY > 250 && mouseY < 250+100) {
// You're in the main menu and Start was clicked
}
if (mouseX > 1420 && mouseX < 1420+400 && mouseY > 650 && mouseY < 650+100) {
// You're in the main menu and Exit was clicked
}
if (mouseX > 1420 && mouseX < 1420+400 && mouseY > 450 && mouseY < 450+100) {
// You're in the main menu and Help was clicked
}
// You should use 'else if' instead of 3 different if, but I coded it like that so it would be easier to see the small differences between the coordinates
case 1:
if (mouseX > 1420 && mouseX < 1420+400 && mouseY > 450 && mouseY < 450+100) {
// You're un the help menu and Back was clicked
}
}
}
As you can see, I just used the coordinates and size of your buttons to check if the click was located inside one. That's kind of ninja-ing my way out of this issue. I don't know how far into programming you are, or else I would recommand to build a class to handle user inputs, but this way is easy to manage for small exercises like homework.
2. Designing controlP5 buttons
I'm not a ControlP5 expert, so we'll keep close to the basics.
I'll be blunt, the code you provided is ripe with problems, and it's not so many lines, so instead of pointing where it goes wrong I'll give you some skeleton code which will work and on which you can build some understanding. I'll give you the tools and then you can make your project work.
When you design your buttons, if you design them all in the same object, they'll share some properties. For an example, all your buttons will be visible or invisible at the same time. You don't need to redraw them all the time, because they already handle this, so you need to manage them with another method.
You should design your buttons as global objects (as you did), and add them to the ControlP5 object which makes the most sense. You can have one button per object if you want, or many if they are linked together, for an example all the "menu" buttons which appears at the same time could be owned by the same object. Design your buttons in the setup() method if you design them only one time for the whole program. Of course, if this was more than an homework, you may want to avoid the buttons being globals, but it'll be much easier to keep them in memory for a short project.
The "name" of the button is also the name of the method that it'll try to call if you click on it. Two buttons cannot share the same "name". Buttons can have a set value which will be sent to the method that they call.
You don't need to use Processing's mouse events for the buttons to work. They are self-contained: they have their own events, like being clicked on or detecting when the mouse is over them. Here's the documentation for the full list of the methods included in the ControlP5 buttons.
You don't need to manage the buttons in the draw() loop. They manage themselves.
Here's some skeleton code to demonstrate what I just said. You can copy and paste it in a new Processing project and run it to see what's going on.
ControlP5 cp5;
ControlP5 flipVisibilityButton;
int Page = 0;
void setup() {
size(1920, 800);
textAlign(CENTER, CENTER);
textSize(60);
fill(255);
cp5 = new ControlP5(this); // this is ONE object, which will own buttons.
cp5.addButton("MenuButton0") // this is the name of the button, but also the name of the method it will call
.setValue(0) // this value will be sent to the method it calls
.setPosition(1420, 250)
.setSize(400, 100);
cp5.addButton("MenuButton1")
.setValue(1)
.setPosition(1420, 450)
.setSize(400, 100);
cp5.addButton("MenuButton2")
.setValue(2)
.setPosition(1420, 650)
.setSize(400, 100);
flipVisibilityButton = new ControlP5(this); // this is a different object which own it's own controls (a button in this case)
flipVisibilityButton.addButton("flipVisibility")
.setValue(2)
.setPosition(200, height/2)
.setSize(200, 100);
}
void draw() {
// No button management to see here
background(0);
// showing which button has been pressed while also keeping watch to see if the mouse is over one of the cp5 buttons
text(Page + "\n" + cp5.isMouseOver(), width/2, height/2);
}
void MenuButton0(int value) {
ChangePage(value);
}
void MenuButton1(int value) {
ChangePage(value);
}
void MenuButton2(int value) {
ChangePage(value);
}
void ChangePage(int value) {
Page = value;
}
void flipVisibility(int value) {
// When the buttons are invisible, they are also unclickable
cp5.setVisible(!cp5.isVisible());
}
You should be able to expand on this example to do your project, but if you have difficulties don't hesitate to comment here and ask further questions. Have fun!
i'm sure I can figure this out on my own but I feel like the way i'm writing it is already too expensive and coupled.
I am writing a simulator with a security robot and a intruder, I have a collision function, where in the 3rd if statement it checks if an intruder (rectangle of width 11) collides with an surveillance camera (arc) and if that happens then I want to activate my function for the security robot to chase the intruder.
<-- Important note: the checkShapeIntersection function is inside a timeLine event so its running constantly -->
private boolean checkShapeIntersection(Shape block) {
//Name to check for intruder and surveillance collision
String Surveillance = "Arc";
boolean collisionDetected = false;
for (Shape static_bloc : nodes) {
if (static_bloc != block) {
Shape intersect = Shape.intersect(block, static_bloc);
if (intersect.getBoundsInLocal().getWidth() != -1) {
collisionDetected = true;
//Checks of intruder collides with an arc (surveillance), the 11th width is only for intruder rectangles
if ( Surveillance.equals(block.getClass().getSimpleName()) && static_bloc.getBoundsInLocal().getWidth() == 11) {
//Activate Chase function
testRobot.chaseIntruder(static_bloc);
detected = true;
}
}
}
}
if (collisionDetected) {
block.setFill(Color.BLUE);
} else {
block.setFill(Color.RED);
}
return detected;
}
And inside my Security Robot Class
public void chaseIntruder(Shape intruder) {
destinationsList.add(new Vector2D(intruder.getLayoutBounds().getMinX(),intruder.getLayoutBounds().getMinY()));
this.updatePosition();
}
You probably want to use multi-threading here, in Java you can implement Runnable or Thread to achieve wanted functionality.
Here are some links with more info:
In a simple to understand explanation, what is Runnable in Java?
https://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html
https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html
https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html
Hope it helps.
I am wondering if there is a bit of code or that can apply a method from a class to all of the objects in the ArrayList? I'm making a basic space invaders program and I am trying to implement a move method that will apply to all of enemies, so that they move in a group rather than individually.
I've created the items in the array list here:
for (int i = 0; i < 6; i++) {
venWidth = venWidth - 139;
enemyList.add(new Venusian("/venusian.jpg", venWidth, height));
}
for (int i = 6; i < 12; i++) {
merWidth = merWidth - 145;
enemyList.add(new Mercurian("/mercurian.jpg", merWidth, merHeight));
}
for (int i = 12; i < 18; i++) {
marWidth = marWidth - 125;
enemyList.add(new Martian("/martian.jpg", marWidth, marHeight));
}
Here is where I call the move method:
for (int i = 0; i < enemyList.size(); i++) {
Invader Invaders = (Invader) enemyList.get(i);
Invaders.draw(g);
Invaders.Move(1024);
This makes them move independently and overlap, at the moment I am just moving them right and left using the boundaries of my created window. So is there any way of moving them together at the same time? I have searched for a way to apply a class method to all of the lists items but I haven't found anything after a couple of hours.
Any material, sources or advice relating to this would be greatly appreciated.
You will have to come up with a solution that can decouple the Invaders you are moving from those you are displaying.
This is due to the fact that your individual Invaders will always be more or less sequentially moved - even if you are working with multiple threads, etc. Even if you would start using Java8 Lambdas to write your code like this:
ArrayList<Invader> badGuys;
//fill your List here
badGuys.forEach( badGuy -> badGuy.move());
This would also create intermediate states where some Invaders were moved, some were not.
So you have to make sure that you only draw a consistent set of Invaders to your screen. You could do this several ways:
Only draw to screen after all Invaders were moved
Make a copy of your invaders for drawing, while the Invaders are being moved. After all Invaders were moved, start displaying the Invaders from the moved List
...
1st Edit: How do you draw the Invaders to screen? Is this happening in separate threads?
3rd EDIT: Okay so maybe you can stop your timerThread before starting to move your Invaders. And when you are finished with moving them you can restart the timer again. Check what methods your timer offers It should have start() and stop() or maybe suspend() methods.
Do something like this:
timer.stop();
badGuys.moveAll();
timer.start();
2nd EDIT: Just looked over your code again. There is no need for you to start your for loop number 2 and 3 from indexes other than 0. Your code will be easier to read if for example you just say:
for (int i = 0; i < 6; i++) { // start from 0 (to 6) instead of 6 to 12
merWidth = merWidth - 145;
enemyList.add(new Mercurian("/mercurian.jpg", merWidth, merHeight));
}
create an interface like Moveable. and put Move method on it. then implement it on Venusian, Martian and Mercurian. and use this interface on arraylist
interface Moveable {
public void Move(int dist);
}
class Mercurian implements Moveable {
public void Move(int dist)
{
//do something
}
}
class Venusian implements Moveable {
public void Move(int dist)
{
//do something
}
}
class Martian implements Moveable {
public void Move(int dist)
{
//do something
}
}
ArrayList<Moveable> enemyList = new ArrayList<Moveable>();
Im trying to get my collision using box2D in jumping game work correct but i have some problems. The player have Box Shape and Platform is just a line made with chainShape.
First problem is that i would like to enable collision only when Player touch Platform with bottom line of it's box. I tried to do that by checking the y coordinates of body but it doesnt worked becouse the diffrence beetween platform and bottom part of box while collision was about 0.5 units.
Second problem is that at the moment the collision is turning on two or three times for same platform in single touch. Here i don't have idea how i can fix it.
Actual code for collision in my code is:
#Override
public boolean shouldCollide(Fixture fixtureA, Fixture fixtureB) {
if(fixtureA == fixture || fixtureB == fixture){
return body.getLinearVelocity().y< 0; //&& (fixtureA.getBody().getPosition().y <= fixtureB.getBody().getPosition().y);
}
return false;
}
#Override
public void preSolve(Contact contact, Manifold oldManifold) {
if(contact.getFixtureA() == fixture || contact.getFixtureB() == fixture){
//System.out.println("Contact A: "+ contact.getFixtureA().getBody().getPosition().y);
//System.out.println("Contact B: "+ contact.getFixtureB().getBody().getPosition().y);
if(contact.getFixtureA().getBody().getPosition().y == contact.getFixtureB().getBody().getPosition().y)
contact.setEnabled(true);
else
contact.setEnabled(false);
}
}
//COLLISION CALCULATION
#Override
public void postSolve(Contact contact, ContactImpulse impulse) {
body.applyLinearImpulse(0, jumpPower, body.getWorldCenter().x, body.getWorldCenter().y, true);
}
Thanks in advance.
[UPDATE] i changed the order a bit so i call the super.act(delta) at the end of the method and it seems to help a bit! But not that sure about it yet.
I got a square system for my map. So its an 2D array and i i make one move the figure does move from one square to the next. While that it's not possible to "stop" the figure between 2 squares. When my characters made one move i check if the Touchpad is touched and if yes i start the next move. While that it seems to lag sometimes and i dont know why!? I really hope you may find the "lag". Here is how i calculate the next move inside the act()of my Actor Character:
#Override
public void act(float delta) {
super.act(delta); // so the actions work
if (moveDone) {
if (screen.gameHud.pad.isTouched()) {
// check in which direction is the touchcontroller
if (screen.gameHud.pad.getKnobPercentX() < 0
&& Math.abs(screen.gameHud.pad.getKnobPercentY()) < Math
.abs(screen.gameHud.pad.getKnobPercentX())) {
// checkt if the |x|>|y|
if (checkNextMove(Status.LEFT)) {
this.status = Status.LEFT;
move(Status.LEFT);
this.screen.map.mapArray[(int) (this.mapPos.x)][(int) this.mapPos.y] = Config.EMPTYPOSITION;
this.screen.map.mapArray[(int) (this.mapPos.x - 1)][(int) this.mapPos.y] = Config.CHARSTATE;
this.mapPos.x--;
moveDone = false;
}
} else if //.... rest is the same just with other directions
else{ //if touchpad isnt touched!
setIdle();
}
updateSprite(delta); //just change the textureRegion if its time for that
} //methode end
Okay so you need some more informations i am sure. Checkmoves like this:
case LEFT:
if (this.mapPos.x - 1 >= 0)
if (this.screen.map.mapArray[(int) (this.mapPos.x - 1)][(int) this.mapPos.y] == Config.EMPTYPOSITION)
return true;
break; //same for all other just direction changin
And the last you need to know is the move(_) i guess. It does add an moveTo Action to my figures.
public void move(Status direction) {
switch (direction) {
case LEFT:
this.addAction(Actions.sequence(
Actions.moveTo((getX() - Config.BLOCK_SIZE), getY(), speed),
moveDoneAction));
break;
moveDoneAction is a simple RunnableAction that set the boolean moveDone to true if its done moving.
i really hope you can help. If you need some more informations please let me know as comment!
There are better tools than StackOverflow for optimizing Android code. Use a profiler and see what is actually happening. Specifically, the traceview profiler: how to use traceview in eclipse for android development? (If you're not using Eclipse, you can use traceview directly via the ADT.)