+ All Categories
Home > Documents > Simple Top Down Car Game -...

Simple Top Down Car Game -...

Date post: 06-Feb-2018
Category:
Upload: dophuc
View: 214 times
Download: 0 times
Share this document with a friend
17
Simple Top Down Car Game Aim – create a top down car racing game where the car must stay on the track. Solution 1. Create a one coloured track. We will then test the colour underneath the car and if it doesn’t match the track colour, then we have left the track. First lets create a really boring track in a graphics editor. Basically open you graphics editor, create a new image of 800,600 and set the paint brush to about 100. If you want your track bigger, then increase this brush stroke. Then simply choose the track colour (grey in my case with red, green and blue of 102,102,102) and draw it. You will end up with something like Don’t worry we will make it look better later. Create a new Scenario. Add a word called Track1 and use your track above as its background. Set the world size to 800,600. Import the SmoothMover class and create a new subclass from it called Car. Choose a car image for it. We are going to create 2 properties for our car – speed, and background colour. public class Car extends SmoothMover { 1
Transcript
Page 1: Simple Top Down Car Game - fionawcs.weebly.comfionawcs.weebly.com/uploads/3/8/2/7/38274585/simple_t…  · Web viewDon’t worry we will make it look better later. ... Place a car

Simple Top Down Car Game

Aim – create a top down car racing game where the car must stay on the track.

Solution 1. Create a one coloured track. We will then test the colour underneath the car and if it doesn’t match the track colour, then we have left the track.

First lets create a really boring track in a graphics editor. Basically open you graphics editor, create a new image of 800,600 and set the paint brush to about 100. If you want your track bigger, then increase this brush stroke. Then simply choose the track colour (grey in my case with red, green and blue of 102,102,102) and draw it. You will end up with something like

Don’t worry we will make it look better later.

Create a new Scenario.

Add a word called Track1 and use your track above as its background. Set the world size to 800,600.

Import the SmoothMover class and create a new subclass from it called Car. Choose a car image for it.

We are going to create 2 properties for our car – speed, and background colour.

public class Car extends SmoothMover{ double speed = 0; Color trackcolour;

You will get a compilation error on the above as we have to import another class to access the Color class. Add this to the top of you Car class –

import java.awt.Color;

1

Page 2: Simple Top Down Car Game - fionawcs.weebly.comfionawcs.weebly.com/uploads/3/8/2/7/38274585/simple_t…  · Web viewDon’t worry we will make it look better later. ... Place a car

As we have used SmoothMover we can set out coordinates and movement in doubles instead of ints. This gives us greater control on movement.

We want this car to run on any track colour so we are going to use a constructor where we can pass in the background colour to use.

//set a default colour for the background public Car (int r, int g, int b){ trackcolour= new Color (r, g, b); }

Our act method will have 3 lines

public void act() { move(speed); checkMovement(); checkonTrack(); }

So we have to create 2 methods for the car movement and to check if we are still on the track.

public void checkonTrack() { World world = getWorld(); //System.out.println(world.getBackground().getColorAt(getX(),getY())); if (!world.getBackground().getColorAt(getX(), getY()).equals(trackcolour)) { move(-1); speed = 0; } }

The above method gets the current background world and gets the color of the background at our current coordinates. We test this against the current trackcolour. If they are not equal then we have left the track. Current we then reverse a little and put the speed to 0.

Note: I have left a commented out line of code here. If you are unsure of you background track colour then place a car on it and uncomment the line above. It will read its r, g and b colours.

public void checkMovement() { if (Greenfoot.isKeyDown("up")) { speed = speed + 0.1; } if (Greenfoot.isKeyDown("down")) { speed = speed - 0.1; } if (Greenfoot.isKeyDown("left")) { turn(-2); } if (Greenfoot.isKeyDown("right")) { turn(2); } }

2

Page 3: Simple Top Down Car Game - fionawcs.weebly.comfionawcs.weebly.com/uploads/3/8/2/7/38274585/simple_t…  · Web viewDon’t worry we will make it look better later. ... Place a car

Check movement simply turns, accelerates, and decelerates the car.

Our total class now looks like this –

public class Car extends SmoothMover{ double speed = 0; Color trackcolour; //set a default colour for the background public Car (int r, int g, int b){ trackcolour = new Color (r, g, b); } public void act() { move(speed); checkMovement(); checkonTrack(); } public void checkonTrack() { World world = getWorld(); //System.out.println(world.getBackground().getColorAt(getX(),getY())); if (!world.getBackground().getColorAt(getX(), getY()).equals(trackcolour)) { move(-1); speed = 0; } } public void checkMovement() { if (Greenfoot.isKeyDown("up")) { speed = speed + 0.1; } if (Greenfoot.isKeyDown("down")) { speed = speed - 0.1; } if (Greenfoot.isKeyDown("left")) { turn(-2); } if (Greenfoot.isKeyDown("right")) { turn(2); } }}

Place a car on the track, save your world and run your game.

3

Page 4: Simple Top Down Car Game - fionawcs.weebly.comfionawcs.weebly.com/uploads/3/8/2/7/38274585/simple_t…  · Web viewDon’t worry we will make it look better later. ... Place a car

Lets create a far nicer looking track. Here is one that I have created using a grass filled back ground and then using the tiles trackVersion3 at http://opengameart.org by TRBRY released under (CC BY 3.0). I then added some trees and scrub age again from opengameart foilage - Warlock's Gauntlet team (CC BY 3.0). This creates a more realistic car track.

Example track tiles

Example use of track tiles on textured background.

4

Page 5: Simple Top Down Car Game - fionawcs.weebly.comfionawcs.weebly.com/uploads/3/8/2/7/38274585/simple_t…  · Web viewDon’t worry we will make it look better later. ... Place a car

Next steps.

Improve the car leaving the tack. At the moment we can reverse off the track. Lets make it harder to leave the track. We will update checkonTrack a little. It will reverse if going forwards, but go forward if reversing into side.

public void checkonTrack() { World world = getWorld(); //System.out.println(world.getBackground().getColorAt(getX(),getY())); if (!world.getBackground().getColorAt(getX(), getY()).equals(trackcolour)) { if (speed>0) { move(-1); } else { move(1); } speed = 0; } }

Lets add a couple of actors that will add to the game.

A static start/finishing line.

Create an actor called startline and import a chequered image.

5

Page 6: Simple Top Down Car Game - fionawcs.weebly.comfionawcs.weebly.com/uploads/3/8/2/7/38274585/simple_t…  · Web viewDon’t worry we will make it look better later. ... Place a car

We can then drop this where we want the start/finish line. If you try your game now, you should notice you go under the start line. Not ideal.

If you look at your world prepare you will have something like –

Car car1 = new Car(77,77,77); addObject(car1, 174, 55); StartLine startline = new StartLine(); addObject(startline, 264, 71); startline.setLocation(256, 64);

we can see the start line is added last. Lets re-arrange it so the car is created after the start line.

StartLine startline = new StartLine(); addObject(startline, 264, 71); startline.setLocation(256, 64); Car car1 = new Car(77,77,77); addObject(car1, 174, 55);

Now we drive over the start line. But this does give us the ability to add objects like tunnels, and bridges where the car would go under the graphic.

I’m going to add a bridge (chabull(CC BY 3.0)).

Add the bridge and save the world again.Because this is an actor we can rotate it and add it anywhere. Also we added it after the car, so the car will go under it.

Lets add an oil spill. Create a black blob in your graphics page. Create an actor called oil spill and add this to the world. Save the world, and move the creation of the oil to the top of the prepare so that we drive over it.

There should be a consequence of driving over oil. We could remove the breaks, accelerate the car, or turn the car randomly or anything we want.

I’m going to add a property called in oil. This will be true if the car is in oil, and will be used to stop the breaks working!

6

Page 7: Simple Top Down Car Game - fionawcs.weebly.comfionawcs.weebly.com/uploads/3/8/2/7/38274585/simple_t…  · Web viewDon’t worry we will make it look better later. ... Place a car

public class Car extends SmoothMover{ double speed = 0; Color trackcolour; boolean inoil = false;

public void checkOil() { if (isTouching(OilSpill.class)) { turn(Greenfoot.getRandomNumber(1)-2); //generate randomnumber between -1 and 1 inoil = true; } else { inoil = false; } }

Modify checkmovementif (Greenfoot.isKeyDown("down") && !inoil) { speed = speed - 0.1; }

Add another car

First we want to add code that does some kind of collision between 2 cars. Simply if we bump on the left the other car moves left and we move right. Add this to car and add a call to the method in act();

public void testForCarCollision() { Actor car = getOneIntersectingObject(Car.class); if (car !=null) { double otherCarX = car.getX(); double otherCarY = car.getY(); //test if other car on left //http://www.mathsisfun.com/algebra/vectors-dot-product.html double angle = Math.atan2(otherCarY - getY(), otherCarX - getX()); if (angle > 0) {// car is on the left turn(-2); } else if (angle < 0) { turn(2); } } }

Add another car.

Its ok driving around, but it would be better if we got to race another car.Lets create 2 new subclasses of Car. Call these Car1, and Car2.

7

Page 8: Simple Top Down Car Game - fionawcs.weebly.comfionawcs.weebly.com/uploads/3/8/2/7/38274585/simple_t…  · Web viewDon’t worry we will make it look better later. ... Place a car

Car1 will look like this –

import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

public class Car1 extends Car{ public Car1 (int r, int g, int b){ super(r,g,b); }}

Car2 will look like this

import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

public class Car2 extends Car{ public Car2 (int r, int g, int b){ super(r,g,b); }}

Note: super means to call its parents (Car) constructor.

Car1 is simply going to use all the methods of Car.Car2 is going to create a new method for checkMovement (this is called method overwriting).

public void checkMovement() { if (Greenfoot.isKeyDown("w")) { speed = speed + 0.1; } if (Greenfoot.isKeyDown("x") && !inoil) { speed = speed - 0.1; } if (Greenfoot.isKeyDown("a")) { turn(-2); } if (Greenfoot.isKeyDown("d")) { turn(2); } }

We do this because we want to use different keys for car control.

More Control Over CarsDuring the next few sections we will be looking at adding more features to the game. To prepare for this we are going to add more properties and a few constants to the car class.

Add the library at the top –

import java.util.*;

8

Page 9: Simple Top Down Car Game - fionawcs.weebly.comfionawcs.weebly.com/uploads/3/8/2/7/38274585/simple_t…  · Web viewDon’t worry we will make it look better later. ... Place a car

public class Car extends SmoothMover{ public static final double MAX_SPEED = 5; public static final double MAX_ACCELERATION = 5; public static final double MAX_BREAKING = 5; public static final int MAX_TURN = 5; double speed = 0; double acceleration = 0.1; double breaking = 0.1; int turnspeed = 2; double laptime; int playerNo; double bestlap; Date startTime; Color trackcolour; boolean inoil = false;

We will update checkMovement to use this.

public void checkMovement() { if (Greenfoot.isKeyDown("up")) { if (speed < MAX_SPEED) { speed = speed + acceleration; } } if (Greenfoot.isKeyDown("down") && !inoil) { if (speed > -MAX_SPEED) { speed = speed - breaking; } } if (Greenfoot.isKeyDown("left")) { turn(-turnspeed); } if (Greenfoot.isKeyDown("right")) { turn(turnspeed); } }

We will make more use of this later.

Checking for a complete lap.We could add a transparent line across the tack and time how long it takes for a car to cross it twice. This would give us a laptime. But it wouldn’t take long for someone to dry over this line, reverse and re-trigger it for a super fast time! We will have to protect against this by using 2 lines that must be triggered in order.

9

Page 10: Simple Top Down Car Game - fionawcs.weebly.comfionawcs.weebly.com/uploads/3/8/2/7/38274585/simple_t…  · Web viewDon’t worry we will make it look better later. ... Place a car

Add 2 more properties to car

boolean checkpoint1triggered = false; boolean checkpoint2triggered = false;

Create a transparent Image of 1 pixel wide, and the height (or greater) than your track width. Also copy this and colour it black, or a different colour from your track. We will use this to place the checkpoint, and then change it to the transparent one later.

Create a new subclass of actor and use the coloured image above.

Drop one at your start line, and another approximately half way through the race.

Save the World so your check points are there.

Update our checkpoints.

Our check point class will look like this

import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

public class CheckPoint extends Actor{ public int checkpointnumber public CheckPoint(int checkpointnum) { checkpointnumber = checkpointnum; } }

We will then have to change the prepare statement in our world to this –

CheckPoint checkpoint = new CheckPoint(1);

And

CheckPoint checkpoint2 = new CheckPoint(2);

Display Lap Times

10

Page 11: Simple Top Down Car Game - fionawcs.weebly.comfionawcs.weebly.com/uploads/3/8/2/7/38274585/simple_t…  · Web viewDon’t worry we will make it look better later. ... Place a car

We are going to modify the constructor, so that we also pass in the player number and store it in playerNo in the object.

public Car (int r, int g, int b,int playernoin){ trackcolour = new Color (r, g, b); playerno = playernoin; }You will have to change the world where we add the cars, to pass in in 1 for the first car and a 2 for the second.

Car1 and Car2 constructors will have to be changed to

public CarX (int r, int g, int b,int playerno){ super(r,g,b,playerno); }

Add this to your world.

public void displayLaptime(double laptime,double bestlap, int playerno,int lapno) { if (playerno == 1) { showText("Laptime : "+laptime+"(s) Best: "+bestlap+" Current Lap: "+lapno,660,670); } }

Add this to Car

public void checkPoints() { CheckPoint checkpoint = (CheckPoint)getOneIntersectingObject(CheckPoint.class); if (checkpoint != null) { //get check point number int cbnumber = checkpoint.checkpointnumber; if (cbnumber == 1) { //at check point 1 if (!checkpoint2triggered && !checkpoint1triggered ) { //if not triggered check point 2. Then new lap checkpoint1triggered = true; Date date = new Date(); startTime = date; } else if (checkpoint2triggered && checkpoint1triggered) {// must be end of lap lapnumber ++; checkpoint2triggered = false; checkpoint1triggered = false; Date enddate = new Date(); laptime = enddate.getTime() - startTime.getTime(); laptime = laptime / 1000.0; if (laptime < bestlap) { bestlap = laptime; } Track2_1200_900 world = (Track2_1200_900)getWorld(); world.displayLaptime(laptime,bestlap,playerno,lapnumber); } }

11

Page 12: Simple Top Down Car Game - fionawcs.weebly.comfionawcs.weebly.com/uploads/3/8/2/7/38274585/simple_t…  · Web viewDon’t worry we will make it look better later. ... Place a car

else { if (!checkpoint2triggered) { checkpoint2triggered = true; } } } }

Add a sand obstacleNext we are going to add a sand obstacle on the road that will slow the cars down. I have drawn one in paint.net here.

Because the image is rectangular, I may have to change the offset a little when finding the collision, or I may even split the image up to four images so that we have less intersection points.

We would then place these together to look like the first image. But first we will go with the large image.

Lets add the sand someone where on your track. We will change the speed in Car to make it public.

public double speed = 0;

In sand we will add the following to act which will limit the speed of the car.

Car car = (Car)getOneIntersectingObject(Car.class); if (car != null) { car.speed = 0.5; }

Increase car Performance

Lets add an actor (Spanner) that when driven over by a car it improves its performance in either top speed, acceleration, breaking or turning.

This will randomly be added to the track.

In your world add

public static final int SPANNER_SPAWN_TIME = 2000; public static final int SPANNER_SPAWN_TIMEOUT = 1000;

12

Page 13: Simple Top Down Car Game - fionawcs.weebly.comfionawcs.weebly.com/uploads/3/8/2/7/38274585/simple_t…  · Web viewDon’t worry we will make it look better later. ... Place a car

private int spannercounter;

public void act() { spannerRewardsAdd(); }

private void spannerRewardsAdd(){ spannercounter ++; if (spannercounter > SPANNER_SPAWN_TIME) { spannercounter = 0; addSpanner(); } } private void addSpanner() { int place = Greenfoot.getRandomNumber(5); if (place == 0) { addObject(new Spanner(SPANNER_SPAWN_TIMEOUT),906,88); } else if (place == 1) { addObject(new Spanner(SPANNER_SPAWN_TIMEOUT),766,536); } else if (place == 2) { addObject(new Spanner(SPANNER_SPAWN_TIMEOUT),597,832); } else if (place == 3) { addObject(new Spanner(SPANNER_SPAWN_TIMEOUT),215,829); } else if (place == 4) { addObject(new Spanner(SPANNER_SPAWN_TIMEOUT),191,98); } }

Create a Spanner class

public class Spanner extends Actor{ int lifetime; int lifecounter; public Spanner(int lifetimein) { lifetime = lifetimein; } public void act() { lifecounter++; if (lifecounter > lifetime) { getWorld().removeObject(this); } } }

13

Page 14: Simple Top Down Car Game - fionawcs.weebly.comfionawcs.weebly.com/uploads/3/8/2/7/38274585/simple_t…  · Web viewDon’t worry we will make it look better later. ... Place a car

We are also going to show a graphic for whatever reward the user gained. We will create another actor called Reward. Also create 5 graphics for the rewards and one non – reward that will stop the car.

public class Reward extends Actor{ public static final int REWARD_SPAWN_TIMEOUT = 200; private int counter=0; GreenfootImage image; public Reward (int rewardtype) { if (rewardtype == 0) { image = new GreenfootImage( "RewardAcel.png" ); } else if (rewardtype == 1) { image = new GreenfootImage( "RewardBreak.png" ); } else if (rewardtype == 2) { image = new GreenfootImage( "RewardSpeed.png" ); } else if (rewardtype == 3) { image = new GreenfootImage( "RewardTurn.png" ); } else if (rewardtype == 4) { image = new GreenfootImage( "RewardStop.png" ); } setImage(image); } public void act() { counter++; if (counter > REWARD_SPAWN_TIMEOUT) { getWorld().removeObject(this); } } }

Adding a Gamepad

14


Recommended