Creating a Car Game in React - Part 2 - Steering and Obstacles
Published: 2019-08-13 06:33:20

---
title: Creating a Car Game in React - Part 2 - Steering and Obstacles
published: true
description: Creating a Car Game in React - Part 2 - Steering and Obstacles
tags: 
---

<link rel="canonical" href="https://www.pmichaels.net/2019/06/07/creating-a-car-game-in-react-part-2-steering-and-obstacles/" />

In the second part of this series, we're going to add some steering to our car, and introduce a concept of obstacles.  If you're wondering what this is the second part of, please start <a href="https://www.pmichaels.net/2019/06/03/creating-a-car-game-in-react-part-1-drawing-and-moving/">here</a>.  

The GitHub repo for this post can be found <a href="https://github.com/pcmichaels/ReactTransAm/tree/Part-Two">here</a>.

In the first post of the series, we added a car, and allowed the user to move it around the screen in a very crude fashion; here, we're going to change the controls to feel a little more like a car.  As with the previous post, not every single change will be here, but it will be in the GitHub repo above.

<h1>Steering and Acceleration</h1>

Let's have a look at the controls in the Game component:

onKeyDown now looks a little different:

    onKeyDown(e) {
	switch (e.which) {
		case 37: // Left
			this.playerSteer(-10);
			break;
		case 38: // Up
			this.playerAccelerate(0.3);
			break;
		case 39: // Right
			this.playerSteer(10);
			break;
		case 40: // Down
			this.playerDecelerate(-0.5);
			break;
		default:
			break;
	}
    } 

So, we're no longer simply repositioning the car, but applying forces to it.  Initially, I had Down as simply a negative acceleration, meaning that if you break too hard, you go backwards!  Here's the three functions referenced above:

    playerAccelerate(speed) {
	this.setState({
		playerMomentum: this.state.playerMomentum + speed
	});
    }

    playerDecelerate(speed) {
	if (this.state.playerMomentum > 0) {
		this.setState({
			playerMomentum: this.state.playerMomentum + speed
		});
	} else if (this.state.playerMomentum < 0) {
		this.setState({
			playerMomentum: this.state.playerMomentum - speed
		});
	}
    }

    playerSteer(direction) {
	this.setState({
		playerRotation: this.state.playerRotation + direction
	});
    }


There are a number of new state variables, which I won't list here.  However, because we are no longer repositioning the car based on the user action, we need to apply the forces that we are changing; that is, we need a game loop.

<h1>Game Loop</h1>

The game loop code is relatively complex.  Looking at this should make you seriously consider using a a game engine of some description:


    gameLoop() { 
	const radians = (this.state.playerRotation - 90) * Math.PI / 180; 
	const aX = (this.state.playerMomentum * Math.cos(radians));
	const aY = (this.state.playerMomentum * Math.sin(radians));
	const velocityX = this.state.playerVelocityX;
	const velocityY = this.state.playerVelocityY;
	const velocitySq = Math.pow(velocityX, 2) + Math.pow(velocityY, 2);
	const posSq = Math.pow(aX, 2) + Math.pow(aY, 2);
	const velocityPosSq = Math.pow(velocityX * aX + velocityY * aY, 2);
	let skidFactor = (posSq == 0 || velocitySq == 0) ? 0 : 1 - (velocityPosSq / posSq / velocitySq);
	
	if (skidFactor <= 0) skidFactor = 0; 
	
	this.setState({
		playerVelocityX: (skidFactor * velocityX) + ((1 - skidFactor) * aX),
		playerVelocityY: (skidFactor * velocityY) + ((1 - skidFactor) * aY)
	}); 
	this.playerMove(
		this.state.playerX + this.state.playerVelocityX,
		this.state.playerY + this.state.playerVelocityY 
	);
	this.playerDecelerate(-(0.1 + skidFactor));
    }

If you're wondering where this brain-melting maths comes from, have a look <a href="https://gamedev.stackexchange.com/questions/172571/how-to-implement-a-slight-skid-in-a-car-game/172575#172575">here</a>.

I've split it up in an effort to make it slightly more understandable, but the premise is that if you're travelling fast and change direction suddenly, it doesn't immediately turn.  Again, if you're thinking you don't want to be messing around with this kind of thing then a lot of game engines take care of this for you.

<h1>Obstacles</h1>

Finally, we have our obstacles.  There is no collision just yet, but this basically puts pictures of trees around the screen (incidentally, I did all the artwork myself, which I assume the reader to be suitably impressed by!)  We'll come back to this later to make the collision work:

    buildObstacles() {
	let obstacles = [];
	const obstacleCount = Math.floor(Math.random() * 10) + 1;
	console.log('Obstacle count ' + obstacleCount);
	for (let i = 1; i <= obstacleCount; i++) {
		const centreX = Math.floor(Math.random() * this.state.windowWidth) + 1;
		const centreY = Math.floor(Math.random() * this.state.windowHeight) + 1;
		
		obstacles.push(<Obstacle key={i} image={treeImg} centreX={centreX} centreY={centreY} width={this.spriteWidth} height={this.spriteHeight} />);
	}
	return obstacles;
    }

All this function does is build up an array of HTML; we then feed that into a class variable in the constructor:

    constructor(props) {
	super(props);
	document.body.style.overflow = "hidden";
	this.state = {
		playerX: 100,
		playerY: 100,
		windowWidth: 1500,
		windowHeight: 1500,
		playerMomentum: 0,
		playerRotation: 0,
		playerVelocityX: 0,
		playerVelocityY: 0
	};
	this.spriteWidth = 25;
	this.spriteHeight = 25;
	this.updateWindowDimensions = this.updateWindowDimensions.bind(this);
	this.onKeyDown = this.onKeyDown.bind(this); 
	this.obstacles = this.buildObstacles(); 
    }

(It's worth noting, as an aside, that we are preventing scrolling here by setting document.body.style.overflow)

Finally, we'll display it in the render method:

    render() { 
	return <div onKeyDown={this.onKeyDown} tabIndex="0">
		<Background backgroundImage={backgroundImg}
		windowWidth={this.state.windowWidth} windowHeight={this.state.windowHeight} /> 
		
		<Car carImage={carImg} centreX={this.state.playerX} 
		centreY={this.state.playerY} width={this.spriteWidth}
		height={this.spriteHeight} rotation={this.state.playerRotation} /> 
		
		{this.obstacles} 
	</div>
    }

This technique allows you to build an array of HTML objects dynamically.  The thing to notice here is the 'key' that we're passing through; if you don't pass this, you'll start getting the following error:

<blockquote>
Each child in a list should have a unique "key" prop.
</blockquote>

In the next post, we'll introduce collision.


<h1>References</h1>

<a href="https://stackoverflow.com/questions/5192983/calculating-x-y-movement-based-on-rotation-angle">https://stackoverflow.com/questions/5192983/calculating-x-y-movement-based-on-rotation-angle</a>

<a href="https://gamedev.stackexchange.com/questions/172571/how-to-implement-a-slight-skid-in-a-car-game">https://gamedev.stackexchange.com/questions/172571/how-to-implement-a-slight-skid-in-a-car-game</a>

<a href="https://stackoverflow.com/questions/39962757/prevent-scrolling-using-css-on-react-rendered-components">https://stackoverflow.com/questions/39962757/prevent-scrolling-using-css-on-react-rendered-components</a>

Originally posted <a href="https://www.pmichaels.net/2019/06/07/creating-a-car-game-in-react-part-2-steering-and-obstacles/">here</a>.