DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • Mastering React App Configuration With Webpack
  • Overcoming React Development Hurdles: A Guide for Developers

Trending

  • Segmentation Violation and How Rust Helps Overcome It
  • Chaos Engineering for Microservices
  • The Modern Data Stack Is Overrated — Here’s What Works
  • Comparing SaaS vs. PaaS for Kafka and Flink Data Streaming
  1. DZone
  2. Coding
  3. JavaScript
  4. Creating a Car Game in React, Part 3: Collision

Creating a Car Game in React, Part 3: Collision

We continue to plug away at building a browser-based game using React.

By 
Paul Michaels user avatar
Paul Michaels
·
Jun. 19, 19 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
12.2K Views

Join the DZone community and get the full member experience.

Join For Free

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 With React

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

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 Scores

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


  • If you enjoyed this article and want to learn more about React, check out this collection of tutorials and articles on all things React.

    Collision (computer science) React (JavaScript library) Collision detection

    Published at DZone with permission of Paul Michaels, DZone MVB. See the original article here.

    Opinions expressed by DZone contributors are their own.

    Related

    • The Cypress Edge: Next-Level Testing Strategies for React Developers
    • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
    • Mastering React App Configuration With Webpack
    • Overcoming React Development Hurdles: A Guide for Developers

    Partner Resources

    ×

    Comments
    Oops! Something Went Wrong

    The likes didn't load as expected. Please refresh the page and try again.

    ABOUT US

    • About DZone
    • Support and feedback
    • Community research
    • Sitemap

    ADVERTISE

    • Advertise with DZone

    CONTRIBUTE ON DZONE

    • Article Submission Guidelines
    • Become a Contributor
    • Core Program
    • Visit the Writers' Zone

    LEGAL

    • Terms of Service
    • Privacy Policy

    CONTACT US

    • 3343 Perimeter Hill Drive
    • Suite 100
    • Nashville, TN 37211
    • support@dzone.com

    Let's be friends:

    Likes
    There are no likes...yet! 👀
    Be the first to like this post!
    It looks like you're not logged in.
    Sign in to see who liked this post!