Tag Archives: [].forEach

Creating a Car Game in React – Part 3 – Collision

In this, the third post of this series, we’re going to add collision to the game. For a full list of the code, please see here.

If you’re wondering about earlier posts, please start here.

Since we’re introducing collision, we’ll also need to introduce the age old game concept of “Lives”. The premise here is that when you crash into something, you lose a life.

The first step is to add a new state variable to hold the player’s remaining lives:

this.state = {
	playerX: 100,
	playerY: 100,
	windowWidth: 1500,
	windowHeight: 1500,
	playerMomentum: 0,
	playerRotation: 0,
	playerVelocityX: 0,
	playerVelocityY: 0,
	playerLives: 3,
	gameLoopActive: false,
	message: ""
};

If you have a look in the repository, there’s a bit of refactoring, where I’ve taken some of the setState code and separated it into logical functions. I won’t list that here.

Collision Detection

At the end of the game loop, we now have a call to check if we’ve collided with anything:

if (this.detectAnyCollision()) {
	this.PlayerDies(); 
}

The collision detection code is quite straight forward, and is based on the simplistic idea that all objects can be considered rectangles. Whilst this is not precise, it’s sufficient for our purpose:

detectAnyCollision() { 
        const halfWidth = this.spriteWidth / 2;
        const halfHeight = this.spriteHeight / 2;

        let rect1 = {x: this.state.playerX - halfWidth, y: this.state.playerY - halfHeight, 
            width: this.spriteWidth, height: this.spriteHeight}

        if (this.detectOutScreen(rect1)) {
            return true;
        }

        return this.obstacles.some(a => {
            var rect2 = {x: a.props.centreX - halfWidth, y: a.props.centreY - halfHeight, 
                width: this.spriteWidth, height: this.spriteHeight}
            
            if (this.detectCollision(rect1, rect2)) {
                return true;
            } else {
                return false;
            }
        });
}

detectCollision(rect1, rect2) {
	if (rect1.x < rect2.x + rect2.width &&
	rect1.x + rect1.width > rect2.x &&
	rect1.y < rect2.y + rect2.height &&
	rect1.y + rect1.height > rect2.y) {
		return true;
	}
	return false;
}

detectOutScreen(rect1) {
	if (rect1.x < 0 || rect1.x + rect1.width > this.state.windowWidth
	|| rect1.y < 0 || rect1.y + rect1.height > this.state.windowHeight) {
		return true;
	}
	return false;
}

The collision detection code itself was pilfered from here. As you can see, all we’re doing is translating our objects into rectangles, and then seeing if they intersect each other, or if the player has left the game area.

Quick note about forEach and some

I had originally used .forEach for the detectAnyCollision() code. Whilst it would, initially make sense to a C# programmer, in fact the Javascript version of this does exactly what it says on the tin; that is, it executes for each element, and there is no way to exit early!

Player Dies and Score

Now that we have introduced collision, we should consider what to do when it happens. The usual thing in a game is that the player either “dies”, or they lose “health”. Since this is inspired by a spectrum game, we’ll go with “dies”. You saw earlier that we introduced the concept of “lives” and, because it was a spectrum, it has to be 3!

The code to deal with the player death is:

PlayerDies() { 
	this.setState({
		playerLives: this.state.playerLives - 1,
		gameLoopActive: false
	});
	if (this.state.playerLives <= 0) {
		this.initiateNewGame();
	} else {
		this.resetCarPosition();
	}
	this.repositionPlayer();
	this.setState({ 
		gameLoopActive: true
	});
}

Just a quick reminder that this isn’t a comprehensive listing of code – please see the GitHub repository for that; however, apart from the reduction in lives, the most important thing here is the gameLoopActive code.

The idea here is that we only execute the game loop while this state variable is set; which means we can stop the game loop while we’re dealing with the player’s collision.

The change in the game loop code for this is very simple:

gameLoop() {
	if (!this.state.gameLoopActive) return;

 . . . 

Crashed Car

All well and good, but as it stands, this simply results in the car stopping when it hits a tree, and then being re-positioned. We can address this by adding a small “animation” to indicate a crash. If you have a look here, you’ll see why I’ve won several awards for my graphics*!

In order to plug this in, we’re going to change the car graphic binding:

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

So, where the crashed flag is set, we’re binding to brokenCarImg; otherwise to carImg; they are defined at the top:

import carImg from '../Assets/Car.png';
import brokenCarImg from '../Assets/Crash.png';

We also split the playerDies() function into two:

playerDying(tillDeath) {
	this.setState({
		playerCrashed: true,
		gameLoopActive: false
	});
	this.stopCar();
	setTimeout(this.playerDies.bind(this), tillDeath);
}

playerDies() { 
	this.setState({
		playerLives: this.state.playerLives - 1,
		gameLoopActive: false
	});
	if (this.state.playerLives <= 0) {
		this.initiateNewGame();
	} else {
		this.resetCarPosition();
	}
	this.repositionPlayer();
	this.setState({ 
		playerCrashed: false,
		gameLoopActive: true
	});
}

All we’re doing here is calling the first function, which effectively just changes the image and then calls the second function on a timeout. Again, don’t forget the `.bind()` when you call timeout, otherwise, you won’t be able to access `this`!

Footnotes

* I haven’t actually won any awards for graphics – I had you fooled, though!

References

https://developer.mozilla.org/en-US/docs/Games/Techniques/2D_collision_detection

https://stackoverflow.com/questions/34653612/what-does-return-keyword-mean-inside-foreach-function/34653650

https://medium.com/@benjamincherion/how-to-break-an-array-in-javascript-6d3a55bd06f6

Playing multiple videos simultaneously using HTML5

I was interested to see how playing multiple videos simultaneously affected the performance of a web page. This probably seems a little like a time machine back to 1995 – I’ll soon be posting about flashing red text and Dreamweaver!

However, playing short videos with only a few frames can be a way to draw attention to a particular part of the page; for example, if you’re browsing a clothing catalogue and one of the models moves when you hover over.

It’s worth pointing out that the entire page will be local, and so I have no network considerations whatsoever. This isn’t, however, about having three Netflix streams running at the same time – it’s short, and small videos.

The video that I’m using came from here. I’m creating an effect whereby you hover over an image of a space ship and it explodes.

MP4

It’s worth bearing in mind that most video formats are not supported by most browsers. MP4 is the exception, so it looks like this is the way to go for video encoding. I used this tool to convert the file.

HTML

Here’s the HTML for a single icon:

<head>
  <script src="HoverAnimate.js"></script>
</head>
<body onload="loaded()">
  <div id="ship1" style="background-image: url('assets/titan.png'); background-repeat: no-repeat; background-size: 50px 50px; width: 50px; height: 50px">
    <video  width="50" height="50" id="ship1-video" 
            style="visibility: hidden">
      <source src="assets/explosion.mp4" type="video/mp4" />
    </video>
  </div>
</body>

Clearly this could be neater if the CSS was separated, but essentially what we have is a div element with a scaled background image, which contains a video (currently hidden). The next thing is the Javascript that plays the video:

function loaded() {
    var imgs = document.getElementsByTagName("div");
    [].forEach.call(imgs, function (item) {
        if (item.style.backgroundImage !== "") {
            item.addEventListener('mouseover', hoverImg, false);
        }
    });
   
}

function hoverImg(e) {      
    var vid = document.getElementById(this.id + "-video");
    vid.onended = function() {        
        vid.style.visibility = 'hidden';
    }
        
    vid.style.visibility = 'visible';
    vid.play();
}

This iterates through all the div elements and, for those that has a background image, hooks up a hover event. I’ve also assumed that the div element will be named using the format “{imagename}-video”.

Conclusion

I tried this with seven videos simultaneously, and didn’t see any jerking of the animations. Whether this would stand up under networked conditions, it’s hard to say, but with the video locally available, performance is fine.

References

https://www.w3schools.com/html/html_media.asp

http://www.online-convert.com/

https://www.w3schools.com/html/html5_video.asp

http://www.dreamincode.net/forums/topic/281583-video-plays-on-mouse-over-but-not-with-multiple-videos/

https://stackoverflow.com/questions/10881678/html-play-a-video-inside-an-image