This site requires JavaScript, please enable it in your browser!
Greenfoot back
JasonZhu
JasonZhu wrote ...

2013/11/21

How to get an object to bounce off a rotatable platform realistically

JasonZhu JasonZhu

2013/11/21

#
How would I code it so that it bounces off realistically?
    public void bounceOff(Actor object)
    {
        int angle = object.getRotation();
        getMovement().setDirection(angle-90);
    }
That is what I have so far. This is puzzling me a great deal, so help is greatly appreciated. I understand that the angle it hits the platform at is the angle it leaves at.
DanPostV2 DanPostV2

2013/11/21

#
this should do the trick! import greenfoot.*; // (World, Actor, GreenfootImage, and Greenfoot) import java.awt.*; import java.awt.image.*; import javax.swing.*; import java.util.List; /** * Plotter is an actor that plots a graph of the population of two * Greenfoot actor classes. You would usually only create one single actor of this class. * * @author M Kolling * @version 0.9 */ public class Plotter extends Actor { private static final Color LIGHT_GRAY = new Color(0, 0, 0, 40); private static JFrame frame; private static GraphPanel graph; private static JLabel stepLabel; private static JLabel count1Label; private static JLabel count2Label; private World world; private int step; private Class class1; private Class class2; /** * Constructor. * * @param width The width of the plotter window (in pixles). * @param height The height of the plotter window (in pixles). * @param startMax The initial maximum value for the y axis. * @param world The world object. * @param class1 The first class to be plotted. * @param width The second class to be plotted. */ public Plotter(int width, int height, int startMax, World world, Class class1, Class class2) { this.world = world; this.class1 = class1; this.class2 = class2; if (frame == null) { frame = makeFrame(width, height, startMax); } else { graph.newRun(); } step = 0; updateGraph(); setImage(new GreenfootImage(1,1)); } /** * Update the plotter graph. */ public void act() { step++; updateGraph(); } /** * Update the graph component in our window with the current object * counts for the two monitored classes. * Stop the simulation if any one of them drops to zero. */ private void updateGraph() { List class1Objects = world.getObjects(class1); List class2Objects = world.getObjects(class2); graph.update(step, class1Objects.size(), class2Objects.size()); if (class1Objects.size()==0 || class2Objects.size()==0) { Greenfoot.stop(); } } /** * Prepare the frame for the graph display. */ private JFrame makeFrame(int width, int height, int startMax) { JFrame frame = new JFrame("Greenfoot actor graph"); frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); Container contentPane = frame.getContentPane(); graph = new GraphPanel(width, height, startMax); contentPane.add(graph, BorderLayout.CENTER); JPanel bottom = new JPanel(); bottom.add(new JLabel(" Step:")); stepLabel = new JLabel(""); bottom.add(stepLabel); bottom.add(new JLabel(" " + class1.getName() + ":")); count1Label = new JLabel(""); bottom.add(count1Label); bottom.add(new JLabel(" " + class2.getName() + ":")); count2Label = new JLabel(""); bottom.add(count2Label); contentPane.add(bottom, BorderLayout.SOUTH); frame.pack(); frame.setVisible(true); return frame; } // ============================================================================ /** * Nested class: a component to display the graph. */ class GraphPanel extends JComponent { private static final double SCALE_FACTOR = 0.8; // An internal image buffer that is used for painting. For // actual display, this image buffer is then copied to screen. private BufferedImage graphImage; private int lastVal1, lastVal2; private int yMax; /** * Create a new, empty GraphPanel. */ public GraphPanel(int width, int height, int startMax) { graphImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); clearImage(); lastVal1 = height; lastVal2 = height; yMax = startMax; } /** * Indicate a new simulation run on this panel. */ public void newRun() { int height = graphImage.getHeight(); int width = graphImage.getWidth(); Graphics g = graphImage.getGraphics(); g.copyArea(4, 0, width-4, height, -4, 0); g.setColor(Color.BLACK); g.drawLine(width-4, 0, width-4, height); g.drawLine(width-2, 0, width-2, height); lastVal1 = height; lastVal2 = height; repaint(); } /** * Dispay a new point of data. */ public void update(int step, int count1, int count2) { Graphics g = graphImage.getGraphics(); int height = graphImage.getHeight(); int width = graphImage.getWidth(); g.copyArea(1, 0, width - 1, height, -1, 0); int y = height - ((height * count1) / yMax) - 1; if (y<0) { scaleDown(); y = height - ((height * count1) / yMax) - 1; } g.setColor(LIGHT_GRAY); g.drawLine(width-2, y, width-2, height); g.setColor(Color.RED); g.drawLine(width-3, lastVal1, width-2, y); lastVal1 = y; y = height - ((height * count2) / yMax) - 1; if (y<0) { scaleDown(); y = height - ((height * count1) / yMax) - 1; } g.setColor(LIGHT_GRAY); g.drawLine(width-2, y, width-2, height); g.setColor(Color.BLACK); g.drawLine(width-3, lastVal2, width-2, y); lastVal2 = y; repaintNow(); stepLabel.setText("" + step); count1Label.setText("" + count1); count2Label.setText("" + count2); } /** * Scale the current graph down vertically to make more room at the top. */ public void scaleDown() { Graphics g = graphImage.getGraphics(); int height = graphImage.getHeight(); int width = graphImage.getWidth(); BufferedImage tmpImage = new BufferedImage(width, (int)(height*SCALE_FACTOR), BufferedImage.TYPE_INT_RGB); Graphics2D gtmp = (Graphics2D) tmpImage.getGraphics(); gtmp.scale(1.0, SCALE_FACTOR); gtmp.drawImage(graphImage, 0, 0, null); int oldTop = (int) (height * (1.0-SCALE_FACTOR)); g.setColor(Color.WHITE); g.fillRect(0, 0, width, oldTop); g.drawImage(tmpImage, 0, oldTop, null); yMax = (int) (yMax / SCALE_FACTOR); lastVal1 = oldTop + (int) (lastVal1 * SCALE_FACTOR); lastVal2 = oldTop + (int) (lastVal2 * SCALE_FACTOR); repaint(); } /** * Cause immediate update of the panel. */ public void repaintNow() { paintImmediately(0, 0, graphImage.getWidth(), graphImage.getHeight()); } /** * Clear the image on this panel. */ public void clearImage() { Graphics g = graphImage.getGraphics(); g.setColor(Color.WHITE); g.fillRect(0, 0, graphImage.getWidth(), graphImage.getHeight()); repaint(); } // The following methods are redefinitions of methods // inherited from superclasses. /** * Tell the layout manager how big we would like to be. * (This method gets called by layout managers for placing * the components.) * * @return The preferred dimension for this component. */ public Dimension getPreferredSize() { return new Dimension(graphImage.getWidth(), graphImage.getHeight()); } /** * This component is opaque. */ public boolean isOpaque() { return true; } /** * This component needs to be redisplayed. Copy the internal image * to screen. (This method gets called by the Swing screen painter * every time it want this component displayed.) * * @param g The graphics context that can be used to draw on this component. */ public void paintComponent(Graphics g) { Dimension size = getSize(); //g.clearRect(0, 0, size.width, size.height); if(graphImage != null) { g.drawImage(graphImage, 0, 0, null); } } } }
Gevater_Tod4711 Gevater_Tod4711

2013/11/21

#
To let your actor bounce off at the worlds edge you can use this method:
    /**
     * Let the actor bounce of of the world edge.
     */
    public void bounceOffWorldEdge()  {
        if (getX() < 20) {
            if (getRotation() < 180) {
                setRotation(180-getRotation());
            }
            else if (getRotation() >= 180) {
                setRotation((180-getRotation()));
            }
            if (getX() < 20) {
                for (int i = 0; i < 5 && getX() < 20; i++) {
                    setLocation(getX()+5, getY());
                }
            }
        }
        else if (getX() > getWorld().getWidth()-20) {
            if (getRotation() <= 90) {
                setRotation(180-getRotation());
            }
            else if (getRotation() > 270) {
                setRotation(180+(360-getRotation()));
            }
            if (getX() > getWorld().getWidth()-20) {
                for (int i = 0; i < 5 && getX() > getWorld().getWidth()-20; i++) {
                    setLocation(getX()-5, getY());
                }
            }
        }
        else if (getY() < 20) {
            if (getRotation() <= 270) {
                setRotation(90+(270-getRotation()));
            }
            else if (getRotation() > 270) {
                setRotation(90-(getRotation()-270));
            }
            if (getY() < 20) {
                for (int i = 0; i < 5 && getY() < 20; i++) {
                    setLocation(getX(), getY()+5);
                }
            }
        }
        else if (getY() > getWorld().getHeight() - 20) {
            if (getRotation() <= 90) {
                setRotation(270+(90-getRotation()));
            }
            else if (getRotation() > 90) {
                setRotation(270-(getRotation()-90));
            }
            if (getY() > getWorld().getHeight() - 20) {
                for (int i = 0; i < 5 && getY() > getWorld().getHeight() - 20; i++) {
                    setLocation(getX(), getY()-5);
                }
            }
        }
    }
DanPostV2 DanPostV2

2013/11/21

#
hi
JasonZhu JasonZhu

2013/11/21

#
Looks like Danpost has an imposter, anyway, I got it bouncing off the world edge, I need it to bounce off a rotatable paddle realistically. I have SmoothMover and Vector Class. SmoothMover:
public abstract class SmoothMover extends Actor
{
    private Vector movement;
    private double exactX;
    private double exactY;
    
    public SmoothMover()
    {
        this(new Vector());
    }
    
    /**
     * Create new thing initialised with given speed.
     */
    public SmoothMover(Vector movement)
    {
        this.movement = movement;
    }
    
    /**
     * Move in the current movement direction.
     */
    public void move() 
    {
        exactX = exactX + movement.getX();
        exactY = exactY + movement.getY();

        super.setLocation((int) exactX, (int) exactY);
    }
    
    public boolean atHorizontalEdge()
    {
        return getY()<5 || getY()>getWorld().getHeight()-5;
    }
    
    public boolean atVerticalEdge()
    {
        return getX()<5 || getX()>getWorld().getWidth()-5;
    }

    /**
     * Set the location using exact (double) co-ordinates.
     */
    public void setLocation(double x, double y) 
    {
        exactX = x;
        exactY = y;
        super.setLocation((int) x, (int) y);
    }
    
    /**
     * Set the location of this actor. Redefinition of the standard Greenfoot 
     * method to make sure the exact co-ordinates are updated in sync.
     */
    public void setLocation(int x, int y) 
    {
        exactX = x;
        exactY = y;
        super.setLocation(x, y);
    }

    /**
     * Return the exact x co-ordinate (as a double).
     */
    public double getExactX() 
    {
        return exactX;
    }

    /**
     * Return the exact y co-ordinate (as a double).
     */
    public double getExactY() 
    {
        return exactY;
    }

    /**
     * Modify the current movement by adding a new vector to the existing movement.
     */
    public void addForce(Vector force) 
    {
        movement.add(force);
    }
    
    /**
     * Accelerate the speed of this mover by the given factor. (Factors less than 1 will
     * decelerate.) The direction remains unchanged.
     */
    public void accelerate(double factor)
    {
        movement.scale(factor);
        if (movement.getLength() < 0.15) {
            movement.setNeutral();
        }
    }
    
    /**
     * Return the speed of this actor.
     */
    public double getSpeed()
    {
        return movement.getLength();
    }
    
    /**
     * Return the current movement of this object (as a vector).
     */
    public Vector getMovement() 
    {
        return movement;
    }
}
Vector:
public final class Vector
{
    double dx;
    double dy;
    int direction;
    double length;
    
    /**
     * Create a new, neutral vector.
     */
    public Vector()
    {
        
    }

    /**
     * Create a vector with given direction and length. The direction should be in
     * the range [0..359], where 0 is EAST, and degrees increase clockwise.
     */
    public Vector(int direction, double length)
    {
        this.length = length;
        this.direction = direction;
        updateCartesian();
    }

    /**
     * Create a vector by specifying the x and y offsets from start to end points.
     */
    public Vector(double dx, double dy)
    {
        this.dx = dx;
        this.dy = dy;
        updatePolar();
    }

    /**
     * Set the direction of this vector, leaving the length intact.
     */
    public void setDirection(int direction) 
    {
        this.direction = direction;
        updateCartesian();
    }
   
    /**
     * Add another vector to this vector.
     */
    public void add(Vector other) 
    {
        dx += other.dx;
        dy += other.dy;
        updatePolar();
    }
    
    /**
     * Set the length of this vector, leaving the direction intact.
     */
    public void setLength(double length) 
    {
        this.length = length;
        updateCartesian();
    }
    
    /**
     * Scale this vector up (factor greater than 1) or down (factor less than 1). 
     * The direction remains unchanged.
     */
    public void scale(double factor) 
    {
        length = length * factor;
        updateCartesian();
    }
    
    /**
     * Set this vector to the neutral vector (length 0).
     */
    public void setNeutral() {
        dx = 0.0;
        dy = 0.0;
        length = 0.0;
        direction = 0;
    }
    
    /**
     * Revert to horizontal component of this movement vector.
     */
    public void revertHorizontal() {
        dx = -dx;
        updatePolar();
    }
    
    /**
     * Revert to vertical component of this movement vector.
     */
    public void revertVertical() {
        dy = -dy;
        updatePolar();
    }
    
    /**
     * Return the x offset of this vector (start to end point).
     */
    public double getX() {
        return dx;
    }
     
    /**
     * Return the y offset of this vector (start to end point).
     */
    public double getY() {
        return  dy;
    }
    
    /**
     * Return the direction of this vector (in degrees). 0 is EAST.
     */
    public int getDirection() {
        return direction;
    }
    
    /**
     * Return the length of this vector.
     */
    public double getLength() {
        return length;
    }

    /**
     * Update the direction and length from the current dx, dy.
     */
    private void updatePolar() 
    {
        this.direction = (int) Math.toDegrees(Math.atan2(dy, dx));
        this.length = Math.sqrt(dx*dx+dy*dy);
    }   
    
    /**
     * Update dx and dy from the current direction and length.
     */
    private void updateCartesian() 
    {
        dx = length * Math.cos(Math.toRadians(direction));
        dy = length * Math.sin(Math.toRadians(direction));   
    }
}
DanPostV2 DanPostV2

2013/11/21

#
@JasonZhu I don't think that will work.
JasonZhu JasonZhu

2013/11/21

#
Ignore DanPostV2's posts please.
samir samir

2014/2/13

#
Hello , i want to know how can i hide an object and then recall it back on my world?? import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Trein here. * * @author (your name) * @version (a version number or a date) */ public class Trein extends Actor { /** * Act - do whatever the Trein wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { if (Greenfoot.isKeyDown("left")) { move(-8); Trein Trein = new Trein(); //addObject(Trein, 480 ,542); } if (Greenfoot.isKeyDown("right")) { move(8); } if(isOffScreen()) { getWorld().removeObject(this); Trein Trein = new Trein(); //getWorld().addObject(Trein, 480 ,542); //worldGame game = new worldGame(); //game.addObject(Trein, 480 ,542); //turn(180); getImage();//.mirrorVertically(); } } public boolean isOffScreen() { boolean verwijderen = false; if (getX() > 795) { verwijderen = true; } return verwijderen; // getx() < 0 - getImage().getHeight()/2|| //getY() > getWorld().getHeight() + getImage().getHeight()/2) //{ //getWorld().removeObject(this); } }
davmac davmac

2014/2/14

#
samir, you should create a new topic for this please.
samir samir

2014/2/21

#
hello, i tryin to get new train on my world when is the first trein disappers. can anyone help me? HERE ARE THE CODE wich i have till now: import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Trein2 here. * * @author (your name) * @version (a version number or a date) */ public class Trein2 extends Treins { private int maxTreins = 1; public void act() { move(); } public void move() { move(5); if (getX() <= 5 || getX() >= getWorld().getWidth() - 5) { getWorld().removeObject(this); createNewTrein2(); } } public void createNewTrein2() { Trein2 newTrein2; newTrein2 = new Trein2(); World world; world = getWorld(); world.addObject(newTrein2, 426, 535); } }
samir samir

2014/2/21

#
nulpointerException is the Error!
danpost danpost

2014/2/21

#
davmac wrote...
samir, you should create a new topic for this please.
please -- start a new discussion thread for this!
samir samir

2014/2/21

#
@ danspot: i have make a new topic, im in kinda rush thats why did'nt see that comment of you/
You need to login to post a reply.