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

2018/11/28

How to use intersects() method

BackFlip125 BackFlip125

2018/11/28

#
So I'm a student that's new to Java and I'm struggling with this project I'm working. I'm suppose to make a program that pulls input from a GUI file and places oil slicks and derby cars into my world. When the derby car intersects with the oil slick it is suppose to increase my strength of the car, increase the x and y speed by 5%, and oil should have one of it's units consumed. I'm having trouble on using the intersect method to do so. Any suggestions? Also I apologize for the code in advance, I know it's messy and probably an eye sore. Big thanks in advance!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.FileDialog;
import java.io.*;
import java.util.Scanner;
/**
 * MyWorld is the "arena" for a demolition derby.
 *
 */
public class MyWorld extends World
{
    private DerbyCar derbyCar; //For derby car added to world from GUI file
    private OilSlick oilSlick; //For oil slick added to world from GUI file
    /**
     * Constructor for objects of class MyWorld.
     *
     */
    public MyWorld()
    {   
        // Create a new world with 800x600 cells with a cell size of 1x1 pixels.
        super(800, 600, 1);
         
 
    }
     
    public void buildNewGame()
    {
        if (Greenfoot.isKeyDown("s")) // when s is pressed, a file is to be selected
           {
                FileDialog fd = null;
                fd = new FileDialog(fd, "For Reading", FileDialog.LOAD);
                fd.setVisible(true);
             
                String fname = fd.getDirectory() + fd.getFile();
             
                File fileReader = new File(fname);
             
                Scanner reader;
             
                try
                {
                    reader = new Scanner(fileReader);
                }
                catch (FileNotFoundException fnfe)
                {
                    return;
                }
                String command = reader.next();
                while (command != null)
                {
                    int startingStrength = reader.nextInt();
                    int startingX = reader.nextInt();
                    int startingY = reader.nextInt();
                     
                     
                    if (command.equalsIgnoreCase("car"))
                    {
                        double xDirection = reader.nextDouble();
                        double yDirection = reader.nextDouble();
                        derbyCar = new DerbyCar(startingStrength, startingX, startingY, xDirection, yDirection);
                        addObject(derbyCar, startingX, startingY);
                    }
                     
                    if (command.equalsIgnoreCase("slick"))
                    {
                        oilSlick = new OilSlick(startingStrength);
                        addObject(oilSlick, startingX,startingY);
                    }
                     
                    if (command.equals("#"))
                    {
                        reader.nextLine();
                    }
                    if (reader.hasNext())
                    {
                        command = reader.next();
                    }
                    else
                    {
                        command = null;
                    }
 
            }
             
                reader.close();
           }
    }
     
     
     
    /**
     * every call to the world's act method should check to see if
     *   the "s" key has been pressed and load file if it has.
     */
    public void act()
    {
        buildNewGame();
         
        
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
 
/**
 * Am OilSlick is a circle wwhich, when cars touch they speed up and
 * gain strength. When touched, am OilSlick will shrink.
 *
 * Note that this class is completely coded for you. You are welcome
 * to modify this code, but you should not need to do so.
*/
public class OilSlick extends Actor
{
    private int radius; // the current size of the Oil Slick
     
    /**
     * Constructor for OilSlick class.
     *
     *   @param initSize the initial radius of the slick
     */
    public OilSlick(int initSize)
    {
        radius = initSize; // set the size
        redraw();          // now that we know the size, we can draw it
    }
     
    /**
     * consumeUnit - reduces the size of the slick by one unit, and returns
     *   true if the slick was successfully shrunk
     *   @return true if the slick had any value left, falde otherwise
     */
    public boolean consumeUnit()
    {
        // if the slick is really already gone, return false
        if (radius==0)
            return false;
           
        // shrink the slick by one unit
        radius--;
         
        // as long as the slick still exists, redraw it.
        if (radius>0)
            redraw();
        else // if it doesn't eist, remove it
            getWorld().removeObject(this);
         
        // if we get here, it's because we had unit(s) to consume
        return true;
    }
     
    //
    //  Internal method to redraw the slick.
    private void redraw()
    {
        // build an image that is just big enough to fit the slick
        GreenfootImage img = new GreenfootImage(radius*2, radius*2);
         
        // all oil is black.
        img.setColor(Color.BLACK);
         
        // draw the slick as an oval (circle).
        img.fillOval(0,0, radius*2, radius*2);
         
        // use the image just built as our new image
        setImage(img);
    }
    
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.List;
 
/**
 * Write a description of class DerbyCar here.
 *
 */
public class DerbyCar extends Actor
{
    // You will likely want to add more instance variables !
    private int strength; // strength of the car
    private int xPosition; // the intial X location of the car
    private int yPosition; // the intial Y location of the car
    private double xSpeed; // the intial X speed of the car
    private double ySpeed; // the intial Y speed of the car
    private OilSlick oilSlick;
    private static Font carStrengthFont; // remember strength drawing font across all cars
    // you will likley want to add more methods. Don't forget about contructor(s)!
     
    //
    // redraws this car's image based on current strength
    //
    private void redraw()
    {
       // if we have not yet built the font for the cars, do so now
       if (carStrengthFont==null)
           carStrengthFont = new Font(true, false, 18);
             
       // build image for the car
       GreenfootImage img = new GreenfootImage("car03-n.png");
        
       // draw strength in white on hood of car.
       img.setColor(Color.WHITE);
       img.setFont(carStrengthFont);
       img.drawString("" + getStrength(), 5, img.getHeight()/3);
        
       // use the image we just built for this car
       setImage(img);
    }
     
    public DerbyCar(int strength, int intialXPosition, int intialYPosition, double Xspeed, double Yspeed)
    {
       this.strength = strength;
       this.xPosition = intialXPosition;
       this.yPosition = intialYPosition;
       this.xSpeed = Xspeed;
       this.ySpeed = Yspeed;
    }
     
    public void rotateCar()
    {
        double degrees = Math.atan(ySpeed / xSpeed) * (180 / Math.PI) - 90;
        int degreesValue = (int) degrees;
        setRotation(degreesValue);
    }
     
    public void carsCollide()
    {
         
    }
     
    /**
     * don't forget to add appropriate javadoc comment(s) here
     */
    public int getStrength()
    {
        return this.strength; // returns current strength
    }
     
     
    /**
     * Act - do whatever the DerbyCar wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act()
    {
        redraw();
        if (this.intersects(oilSlick))
        {
            xSpeed = xSpeed * .05;
            ySpeed = ySpeed * .05;
        }
        if (getY() == 0 || getY() == getWorld().getHeight()-1) /** top or bottom */
        {
            setRotation(360-getRotation());
            ySpeed = -ySpeed;
            strength --;
        }
        if (getX()==0 || getX() == getWorld().getWidth()-1) /** left or right */
        {
            setRotation(180-getRotation());
            xSpeed = -xSpeed;
            strength --;
        }
        if(strength <= 0)
        {
            int newX = getX();
            int newY = getY();
            OilSlick oilSlick = new OilSlick(50);
            getWorld().addObject(oilSlick, newX, newY);
            getWorld().removeObject(this);
        }
        rotateCar();
        xPosition += xSpeed;
        yPosition += ySpeed;
        setLocation(xPosition, yPosition);
         
    }   
}
danpost danpost

2018/11/28

#
BackFlip125 wrote...
When the derby car intersects with the oil slick it is suppose to increase my strength of the car
Is that really what you want? That is not very realistic. Normally, when a car hits an oil slick, it just loses friction with the road, tending the car to move only by its current momentum.
increase the x and y speed by 5%
This appears to already by implemented. However, again, is this really what you want? and, do you want this to repeatedly happen each act cycle the car intersects the oil slick?
and oil should have one of it's units consumed.
Repeating for each act cycle the car intersects the oil slick.
BackFlip125 BackFlip125

2018/11/28

#
According to the project details.. yes the strength is suppose to increment by 1, as opposed when it runs into a wall or other car it decrements by 1. As for the speed, the code is in the implemented, but when the program is ran, the car just runs into the oil slick and stops as if its being blocked, instead of going through it and speeding up through it. And for the last part, yes it should repeat for each time the car intersects the oil slick. sorry if that was misleading
BackFlip125 BackFlip125

2018/11/29

#
I also have a MyVector class and I'm having trouble using this to get a realistic collision between two cars. I need to figure out the directional vector. The x component for this is the difference between the other car's x location and the current car's x location, and similarly the same for y component. The directional vector should run from the current car to a car it is colliding with (the pos/neg of the difference plays a factor here). If the car is moving away from the other car already, then they should not collide, and that's where the dot product method comes into play. using this on the car's velocity, if the answer is > 0, then they are moving away from one another. And I also need help with getting the projection of the car's velcoity into the directional vector, which is also in the MyVector class. Any help is much appreciated!!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
public class MyVector 
{
    /**
     * attribute indicating x component of this vector.
     */
    protected double xComponent;
    /**
     * attribute indicating y component of this vector.
     */
    protected double yComponent;
 
    /**
     * Constructor for objects of class MyVector;
     *   given an x-component and y-component, initializes the vector accordingly
     *  
     *   @param xComponent the x direction value for the vector
     *   @param yComponent the y direction value for the vector
     */
    public MyVector(double xComponent, double yComponent)
    {
        this.xComponent=xComponent;
        this.yComponent=yComponent;
    }
     
     /**
     * Constructor for objects of class MyVector;
     *   uses another vector to initialize this one
     *  
     *   @param other the vector to use to copy into the new vector
     */
    public MyVector(MyVector other)
    {
        xComponent=other.xComponent;
        yComponent=other.yComponent;
    }
     
    /**
     * returns the "strength" of this vector as a scalar
     *
     * @return the calculated magnitude
     */
    public double magnitude()
    {
        return Math.sqrt(xComponent*xComponent+yComponent*yComponent);
    }
     
     
    /**
     * adds the passed in vector to the current vector
     *
     * @param  otherVector   the vector to add to this one
     */
    public void addTo(MyVector otherVector)
    {
 
        xComponent+=otherVector.xComponent;
        yComponent+=otherVector.yComponent;
    }
 
    /**
     * subtracts the passed in vector from the current vector
     *
     * @param  otherVector   the vector to subtract from this one
     */
    public void subFrom(MyVector otherVector)
    {
        xComponent-=otherVector.xComponent;
        yComponent-=otherVector.yComponent;
    }
 
 
    /**
     * calculates the vector dot product of this vector with the passed in vector
     *
     * @param  withThis  the other vector to use in the dot product
     * @return  the value of the dot product
     */   
    public double dotProd(MyVector withThis)
    {
       return withThis.xComponent*xComponent + withThis.yComponent*yComponent;
    }
 
    /**
     * returns a new vector with the "strength" of this vector increased by the passed in scalar
     *    factor. Note that this does NOT modify "this" vector, it just returns a new one.
     *
     * @param  scalar   the value to increase the strength of the vector by.
     * @return  a new vector representing the scalar multiplication
     *
     */ 
    public MyVector scalarMul(double scalar)
    {
        return new MyVector(scalar*xComponent, scalar*yComponent);
    }
     
     
     /**
     * returns the projection of this vector onto the vector being passed in. Note that this does
     *     NOT modify "this" vector, it just returns a new one.
     *
     * @param  onto   the vector onto which we want to project
     * @return  a new vector representing the amount of this vector going on the direction of the "onto" vector
     */ 
    public MyVector proj(MyVector onto)
    {  
        double factor= dotProd(onto)/onto.dotProd(onto);
        
        return onto.scalarMul(factor);
    }
 
}
danpost danpost

2018/11/29

#
BackFlip125 wrote...
yes it should repeat for each time the car intersects the oil slick. sorry if that was misleading
Maybe a misunderstanding here. I did not mean each time the car intersects (hits, or first comes in contact) with an oil slick. I meant the continuous intersecting of the same hit. For one car/oil slick collision, there will be some time of interaction. This will most undoubtedly take a number of act cycles. I was asking if these things that you want done, we to be executed once per collision (regardless of how long the intersecting lasts) or executed once for each act cycles (dependent on intersecting time).
You need to login to post a reply.