I'm trying to get a baby to kick a ball into the goal. So far I have managed to get the ball to go into the goal when the baby touches it by using move(-300); to go into the desired position, but that isn't technically getting the baby to hit the ball into the goal, because the baby can hit it from any direction and it will go into the goal.
I would just like to know the right code to use, I don't need to know the exact solution; I can learn the code and work it out myself but I have literally no idea where to start.
I struggle quite a lot with this particular type of language so my last resort is to ask online.
Thanks for any help and please comment for any additional information.
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class ball here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class ball extends Actor
{
/**
* Act - do whatever the ball wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
playerHitIt();
}
public void playerHitIt()
{
Actor player;
player=getOneObjectAtOffset(0,0,player.class);
if (player !=null)
{
setLocation(getX()-4, getY());
}
}
}
You could start by asking what a Ball is. It's probably not something that should act()* and have playerHitIt() at least unqualifed by which way it was hit. It probably has a field(s) representing position, and probably a velocity. If you consult the Actor API, you'll see the ball has the built-in capacity to do probably all you want because of extending Actor. This and other greenfoot documentation is the place to start. Surely the player is or is controlling an Actor object with its own direction as well, and kicking happens when they intersect.
just provide an empty implementation act(){}
Related
I just started to write the game of snakes in java. (See this if you don't know what that is: http://codeincomplete.com/projects/snakes/ or http://elgoog.im/snake/). So, when the snake eats an object, its tail grows. In order for the turning physics of the game to work properly, each segment of the tail needs to have its own java.awt.Rectangle hitbox. My question is how can I link these hitboxes/segments of his tail so they always stay together, but are seperate components on my JPanel. Otherwise, if there is a better way to do this then let me know. Thanks.
There s should be a snake object, with a ordered set of simple snake piece, each piece showing type. Practice model view controller, each Snake piece should know nothing about graphics. When you at a segment, put by the last noon trail piece. So, your Snake would contain a list of pieces, like this:
List<SnakePieces> mPieces
SnakePieces should be simple, something like this
public class SnakePieces {
public enum Type {Head,Body,Tail};
public Type type;
}
Feel free to add other functions to SnakePieces as required. When you add a new piece, add it at the location
mSnakePieces.add(mSnakePieces.length()-1,newSnakePiece);
If you can, separate out the model (Snake movement), the view (Puts in the graphics for the piece depending on the type of SnakePiece), and the Controller (Feeds the inputs to the model). That's more advanced than required, but helpful. See Wikipedia on Model View Controller.
Also, see the Android Snake Game, which no doubt has some similarities to your application. Android does it via this:
/**
* mSnakeTrail: a list of Coordinates that make up the snake's body
* mAppleList: the secret location of the juicy apples the snake craves.
*/
private ArrayList<Coordinate> mSnakeTrail = new ArrayList<Coordinate>();
It just knows to draw the first and last tiles slightly differently.
I am in this AP class in highschool and we are using the program JAVA or OOP, I don't even know what it is. In the class we don't have a teacher so we basically have to self teach our self from a packet. I am learning how to draw a face and i am kind off struggling.
Well first off, the prompt here- http://mrlanda.com/ecs/unit%205/Happy%20Face.htm
Look at the picture below to see how it looks like.
MY QUESTION-- Well here is what i got so far and it is stressing me out so much, I DON'T KNOW WHY BUT MY LINE KEEPS GOING IN AN ANGLE. Why does it go in an angle when I am not telling it too.. I am also having a problem with the nose i can't seem to find the spot i want to put it at it keeps going into an angle for some reason.
My code so far
import apcslib.*;
public class DrawSquare
{
public static void main(String[] args)
{
DrawingTool marker;
SketchPad poster;
poster= new SketchPad(600,600);
marker= new DrawingTool(poster);
//left side of box
marker.up();
marker.move(0,0);
marker.down();
marker.turnRight(180);
marker.forward(200);
//mouth
marker.up();
marker.move(40,60);
marker.down();
marker.turnRight(90);
marker.forward(100);
//nose
marker.up();
marker.move(100,100);
marker.down();
marker.turnRight(90);
marker.forward(100);
}
}
According to the API docs for DrawingTool the method move(double, double) changes the direction of your drawing tool.
Hence if you perform the move to (40,60) from the endpoint (-200,0) of your previous forward move your new direction vector will be (240,60). When rotating this by 90 degrees you will head in direction of (60,-240).
I've made a sketch showing the behaviour (not exactly to scale - I hope I haven't mixed coordinates)...
So you have the following options to fix this:
instead moving to (40,60) directly you could move to a temporary point before forcing the move to have your desired direction:
// mouth
marker.up();
marker.move(40,50);
marker.move(40,60); // now you have direction "up"
marker.down();
marker.forward(100);
or you could just use move instead of `forward
// mouth
marker.up();
marker.move(40,60);
marker.down();
marker.move(40,160); // or whatever your expected target is...
I'm having an issue with sprite movement, and I'm not sure how to deal with it.
When I set a destination for my player sprite (by clicking the screen), it sets the player moving in that direction. Unfortunately, the player sort of... oscillates. He sort of shivers along the path.
I've set up a test project using just graphics primitives (graphics.fillRect(x,y,w,h)), and its really easy to see. Here's a sort of example without using video/gifs:
My code looks like this
public void tick() {
if (InputHandler.leftClick.heldDown) {
dest.setLocation(InputHandler.leftClick.xPos, InputHandler.leftClick.yPos);
}
direction.setLocation(dest.getX() - position.x, dest.getY() - position.y);
direction.normalize();
position.add(direction.multiply(velocity));
}
This is a really really basic movement system because I'm having the same issues elsewhere and I wanted to work on them in a more controlled environment.
The weirdest part about this is that when the player arrives, he still just sits on one point, shivering madly.
Can anyone help?
There's a little discrepancy? between what you said, "clicking on the screen" and heldDown. Have you read about mouse event handlers? But I see that you want to go on a tick by tick basis. It would be more clear to have a boolean flag that alerts you if the path was changed. Then this segment would look like
if (leftclicked) {
dest.setLocation(InputHandler.leftClick.xPos, InputHandler.leftClick.yPos);
leftclicked = false;
}
...
Strictly, in physics, velocity is a vector. It has both direction and magnitude. If you intend this as simply a speed at which the thing can move, with instant turning, the next three lines should be fine, although the readability seems improvable. (You have to be sure of what all the helper methods are doing. I'd probably prefer to do whatever calculations needed right here in one place.)
However I suspect you do have velocity as something like vector. There is some notion of momentum in here. I think the multiply() method is implemented strangely. If it adds/combines the angle of velocity with the angle of direction behavior like this results. Having an aspect of momentum is cool but if desired you should really think how to do it.
Another explanation is that the code you've shown works as intended, inching the thing along the direction of the black line, but some other part of your code is messing with position. We weren't given a picture of what happens on arrival...
One more thing about readability. It's very important..."really really basic" things can be buggy swamps without simple organizing steps. I have to rewrite implementations several times because I get overeager and miss designs. It looks like you are doing well at my bane, the "one method/object does one thing (well)" principle but getting into trouble with...naming, of all things. Example: direction.setLocation() Now, directions do not have locations. Repeat: directions do not have locations. Also, directions don't need to be normalized - they don't have lengths.
Instead:
direction = new Direction(dx, dy);
position.add(direction.multiply(MOVEMENT_SPEED));//assuming constant speed
where
//sensible encapsulation of "direction"
class Direction {
double angle;//angle in degrees
//constructs a direction from cartesian coordinates
Direction(int x, int y){
angle = Math.toDegrees(Math.atan((double)y/x));
}
//create a vector of specified length in this direction
java.awt.Point multiply(double amt){
return new java.awt.Point(amt*Math.cos(angle), amt*Math.sin(angle))
}
...
}
Hmm long answer...please try for crystal clear code and questions in future! :)
I am developing an AI simulation of predator and prey. I would like to simulate the AI hiding behind obstacles, if it is being chased. But I am still trying to figure out the best way to implement this.
I was thinking along the lines of checking on which side of the obstacle the predator is on and trying to go on the opposite side. Maybe using the A* path finding algorithm to ensure that it gets there using the shortest path.
Now the main reason I am writing is in case somebody is able to point me in the right direction of implementing this (maybe somebody has done this before) or have any other good ideas how to implement it. I have never done anything like this before in terms of programming AI or making any game.
All the obstacles are either horizontal or vertical squares/rectangles.
Please note that the circle in red is the predator while the circle in green is the prey being chased.
I can't give any code off the top of my head, but I can tell you a few things:
First, you need to define the goal of this program. For this case, it is to get the AI to hide behind an obstacle, keeping the user and the AI on opposite sides whenever possible.
Next, you need to decide what needs to be done inside the code (without writing any real code) to accomplish this goal. For instance:
We need to determine what "zone" of the scene is considered "behind the obstacle"
Next, we need to determine a path for the AI to get to that zone without going through the obstacle.
Lastly, we need to add some sort of delay to this so the AI doesn't constantly change its mind for every pixel the user moves across the screen
This isn't per se an easy problem, but it is certainly achievable without breaking too much of a sweat. I'd recommend you find a way, even if it is slow and requires a ton of code, then write the code for it, and lastly refine. If you worry about refinement, then you never get any of the problem solved.
HINT: Determine a vector that points from the player to the middle of the obstacle. Then, multiply the vector by 2 and add it to the position of the player and that gives you a point on the other side of the obstacle (assuming it is a rectangle). Apply a Math.min() or Math.max() restrictor to the x and y values you get to keep the AI as close or far from the obstacle as you wish. That should be a decent start! :)
Update -- I decided to add some code!
// This assumes a few variables:
int obstacleCenterX, obstacleCenterY;
int aiX, aiY, aiWalkSpeed;
int predatorX, predatorY;
private void updateAIMovement() {
int slope_x = obstacleCenterX - predatorX;
int slope_y = obstacleCenterY - predatorY;
int destination_x = predatorX + (slope_x * 2);
int destination_y = predatorY + (slope_y * 2);
if(aiX != destination_x){
aiX += (slope_x / Math.abs(slope_x)) * aiWalkSpeed;
}
if(aiY != destination_y){
aiY += (slope_y / Math.abs(slope_y)) * aiWalkSpeed;
}
}
I have not tested anything at all, but I think this might be somewhat of a right path to take. I could have done A LOT to improve just that little code snippet, but I didn't (such as some trig to make sure the player moves at a true speed when going diagonally, etc...)
Hopefully this helps a little!
I would check if there is something crossing the direct line between x and each observer. If it is, x is hidden.
I have encountered a problem, for which no matter how long I study the API's of the class and superclasses, I can not figure out.
Suppose I wish to design a sort of a game where the mouse motion controls the motion of a block that is used to bounce a ball, which then destroys multi colored bricks.
How do you specifically make the block "listen" to the mouse?
The below code is what I have attempted to achieve the desired results.
/** Breakout Program*/
public class Breakout extends GraphicsProgram implements MouseMotionListener {
...
/** The Paddle Itself */
private GRect paddle = new GRect(0, HEIGHT-PADDLEBOTTOM_OFFSET, PADDLEWIDTH, PADDLEHEIGHT);
...
/** Run the Breakout program. */
public void run() {
paddle.setFillColor(Color.BLACK);
paddle.setFilled(true);
add(paddle);
paddle.addMouseListener(this);
...
}
/** Move the horizontal middle of the paddle to the x-coordinate of the mouse position -
* -but keep the paddle completely on the board. */
public void mouseMoved(MouseEvent e) {
GPoint p= new GPoint(e.getPoint());
double x = p.getX();
paddle.setLocation(x, HEIGHT-PADDLEBOTTOM_OFFSET);
}
}
Any clarification on why/what I am doing incorrectly would be helpful, thanks.
Your class is all set to be used as a mouse listener -- you just have to tell some component to send you MouseEvents. In order to do that, you need to implement MouseMotionListener, which you've already done, so you're most of the way there.
All that's left to do is call the method addMouseMotionListener(this) on your JFrame, JDialog, or whatever window you're using.
In the future, it may be worth setting up a separate class to serve as the listener, just to keep your code straight; the most common solution is called an anonymous inner class, which you may want to Google. But with your deadline approaching, what you've got will work fine.
After mouseMoved() updates the paddle location, you would typically invoke repaint() on the display component. Is there anything in GraphicsProgram apropos to this?
It looks like all of the classes belong to your application, so I am guessing you are working with AWT or Swing.
Try calling repaint() on the paddle.
Just an extra comment to "Etaoin", when you get time and if you are serious about doing OO well, do a search on "is-a" and "has-a" relationships in OO.
If the "is-a" relationship holds true (an apple "is-a" fruit) then its legitimate to use the implements on the class, otherwise if its a "has-a" relationship (a car "has-a" wheel, but a car "is-not-a" wheel) then implements is NOT appropriate - you need to use composition, in other words a member variable of the class.
In your code, can you say that the Breakout class "is-a" MouseMotionListener? The answer is "no", BTW! Breakout "is-a" game, or is an application, but the MOuseMotionListener is part of the implementation.
As "Etaoin" has said, you should implement the MouseMotionListener as an inner class, though I prefer private inner classes, not anonymous classes (to keep the constructor short and to the point, among other reasons).
When you "get" OO, its great and very powerful, but takes real effort to make the "paradigm shift" from procedural thinking.