├── .all-contributorsrc ├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── PULL_REQUEST_TEMPLATE └── workflows │ └── codeql-analysis.yml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── package.json ├── public ├── favicon.ico ├── index.html ├── logo192.png ├── logo512.png ├── manifest.json └── robots.txt ├── src ├── App.js ├── Camera.js ├── Cube.js ├── Ground.js ├── Player.js ├── PointerLockControls.js ├── dirt.jpg ├── grass.jpg ├── index.css ├── index.js ├── serviceWorker.js ├── setupTests.js ├── state.js ├── useCubeStore.js └── usePlayerControls.js └── yarn.lock /.all-contributorsrc: -------------------------------------------------------------------------------- 1 | { 2 | "files": [ 3 | "README.md" 4 | ], 5 | "imageSize": 100, 6 | "commit": false, 7 | "contributors": [ 8 | { 9 | "login": "satansdeer", 10 | "name": "Maksim Ivanov", 11 | "avatar_url": "https://avatars.githubusercontent.com/u/450319?v=4", 12 | "profile": "http://maksimivanov.com", 13 | "contributions": [ 14 | "maintenance" 15 | ] 16 | }, 17 | { 18 | "login": "mockingbird001", 19 | "name": "Phawat Nasompong", 20 | "avatar_url": "https://avatars.githubusercontent.com/u/41034406?v=4", 21 | "profile": "https://github.com/mockingbird001", 22 | "contributions": [ 23 | "maintenance" 24 | ] 25 | }, 26 | { 27 | "login": "christianaurichzm", 28 | "name": "Christian Aurich", 29 | "avatar_url": "https://avatars.githubusercontent.com/u/36874062?v=4", 30 | "profile": "https://www.linkedin.com/in/christian-aurich-zm/", 31 | "contributions": [ 32 | "maintenance" 33 | ] 34 | }, 35 | { 36 | "login": "parweb", 37 | "name": "chris", 38 | "avatar_url": "https://avatars.githubusercontent.com/u/174339?v=4", 39 | "profile": "http://www.parweb.fr/", 40 | "contributions": [ 41 | "maintenance" 42 | ] 43 | } 44 | ], 45 | "contributorsPerLine": 7, 46 | "projectName": "minecraft-react", 47 | "projectOwner": "satansdeer", 48 | "repoType": "github", 49 | "repoHost": "https://github.com", 50 | "skipCi": true 51 | } 52 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE: -------------------------------------------------------------------------------- 1 | Fixes # 2 | 3 | ## Proposed Changes 4 | 5 | - 6 | - 7 | - 8 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches: [ master ] 17 | pull_request: 18 | # The branches below must be a subset of the branches above 19 | branches: [ master ] 20 | schedule: 21 | - cron: '35 20 * * 6' 22 | 23 | jobs: 24 | analyze: 25 | name: Analyze 26 | runs-on: ubuntu-latest 27 | permissions: 28 | actions: read 29 | contents: read 30 | security-events: write 31 | 32 | strategy: 33 | fail-fast: false 34 | matrix: 35 | language: [ 'javascript' ] 36 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] 37 | # Learn more: 38 | # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed 39 | 40 | steps: 41 | - name: Checkout repository 42 | uses: actions/checkout@v2 43 | 44 | # Initializes the CodeQL tools for scanning. 45 | - name: Initialize CodeQL 46 | uses: github/codeql-action/init@v1 47 | with: 48 | languages: ${{ matrix.language }} 49 | # If you wish to specify custom queries, you can do so here or in a config file. 50 | # By default, queries listed here will override any specified in a config file. 51 | # Prefix the list here with "+" to use these queries and those in the config file. 52 | # queries: ./path/to/local/query, your-org/your-repo/queries@main 53 | 54 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 55 | # If this step fails, then you should remove it and run the build manually (see below) 56 | - name: Autobuild 57 | uses: github/codeql-action/autobuild@v1 58 | 59 | # ℹ️ Command-line programs to run using the OS shell. 60 | # 📚 https://git.io/JvXDl 61 | 62 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 63 | # and modify them (or add more) to build your code if your project 64 | # uses a compiled language 65 | 66 | #- run: | 67 | # make bootstrap 68 | # make release 69 | 70 | - name: Perform CodeQL Analysis 71 | uses: github/codeql-action/analyze@v1 72 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | satansdeer@gmail.com. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Thank you for willing to contribute! 4 | 5 | ## Project setup 6 | 7 | 1. Fork and clone the repo 8 | 2. Run `yarn && yarn start` to install dependencies and run the project. 9 | 3. Create a branch for your PR with `git checkout -b pr/your-branch-name` 10 | 11 | ## Help needed 12 | 13 | Please checkout the [the open issues][issues] 14 | 15 | Also, please watch the repo and respond to questions/bug reports/feature 16 | requests! Thanks! 17 | 18 | [issues]: https://github.com/satansdeer/minecraft-react/issues 19 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Maksim Ivanov 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

Minecraft React

2 | 3 | --- 4 | 5 | 6 | [![All Contributors](https://img.shields.io/badge/all_contributors-4-orange.svg?style=flat-square)](#contributors-) 7 | 8 | 9 | 10 | This is a block-based game implementation using [React Three Fiber](https://github.com/pmndrs/react-three-fiber). 11 | 12 | Here is a [video](https://www.youtube.com/watch?v=Lc2JvBXMesY) showing how it was written. 13 | 14 | ## Running The Code 15 | 16 | To run the project clone the repository and run `yarn && yarn start` to launch the app. 17 | 18 | ## Contributors ✨ 19 | 20 | Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)): 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 |

Phawat Nasompong

🚧

Christian Aurich

🚧

chris

🚧

Maksim Ivanov

🚧
33 | 34 | 35 | 36 | 37 | 38 | 39 | This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome! 40 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "minecraft-react", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@react-three/cannon": "^2.3.5", 7 | "@react-three/drei": "^7.0.2", 8 | "@testing-library/jest-dom": "5.11.4", 9 | "@testing-library/react": "11.0.2", 10 | "@testing-library/user-event": "12.1.4", 11 | "nanoid": "3.1.12", 12 | "react": "^17.0.2", 13 | "react-dom": "^17.0.2", 14 | "react-merge-refs": "1.1.0", 15 | "react-scripts": "^4.0.3", 16 | "react-three-fiber": "^6.0.13", 17 | "recoil": "0.0.10", 18 | "three": "^0.129.0" 19 | }, 20 | "scripts": { 21 | "start": "react-scripts start", 22 | "build": "react-scripts build", 23 | "test": "react-scripts test", 24 | "eject": "react-scripts eject" 25 | }, 26 | "eslintConfig": { 27 | "extends": "react-app" 28 | }, 29 | "browserslist": { 30 | "production": [ 31 | ">0.2%", 32 | "not dead", 33 | "not op_mini all" 34 | ], 35 | "development": [ 36 | "last 1 chrome version", 37 | "last 1 firefox version", 38 | "last 1 safari version" 39 | ] 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/satansdeer/minecraft-react/57810f994f6a3862eedd2e3de88b9a3fc1356557/public/favicon.ico -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/satansdeer/minecraft-react/57810f994f6a3862eedd2e3de88b9a3fc1356557/public/logo192.png -------------------------------------------------------------------------------- /public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/satansdeer/minecraft-react/57810f994f6a3862eedd2e3de88b9a3fc1356557/public/logo512.png -------------------------------------------------------------------------------- /public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /src/App.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { RecoilRoot } from 'recoil'; 3 | import { Canvas } from 'react-three-fiber'; 4 | import { Sky } from '@react-three/drei'; 5 | import { Vector3 } from 'three'; 6 | import { Physics } from '@react-three/cannon'; 7 | 8 | import { Ground } from './Ground'; 9 | import { Camera } from './Camera'; 10 | import { Player } from './Player'; 11 | import { Cube } from './Cube'; 12 | import { useCube } from './useCubeStore'; 13 | 14 | const Cubes = () => { 15 | const cubes = useCube(); 16 | return [, ...cubes]; 17 | }; 18 | 19 | const App = () => ( 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | ); 34 | 35 | export default App; 36 | -------------------------------------------------------------------------------- /src/Camera.js: -------------------------------------------------------------------------------- 1 | import React, { useRef, useEffect, useLayoutEffect } from 'react'; 2 | import { useThree } from 'react-three-fiber'; 3 | 4 | export const Camera = props => { 5 | const ref = useRef(); 6 | const { set, size } = useThree(); 7 | 8 | useLayoutEffect(() => { 9 | if (ref.current) { 10 | ref.current.aspect = size.width / size.height; 11 | ref.current.updateProjectionMatrix() 12 | } 13 | }, [size, props]); 14 | 15 | useEffect(() => { 16 | set({ camera: ref.current }); 17 | // eslint-disable-next-line 18 | }, []); 19 | 20 | return ; 21 | }; 22 | -------------------------------------------------------------------------------- /src/Cube.js: -------------------------------------------------------------------------------- 1 | import React, { useState } from 'react'; 2 | 3 | import { useBox } from '@react-three/cannon'; 4 | 5 | import dirt from './dirt.jpg'; 6 | import { TextureLoader } from 'three'; 7 | 8 | import { useSetCube } from './useCubeStore'; 9 | 10 | export const Cube = props => { 11 | const [hover, set] = useState(null); 12 | const addCube = useSetCube(); 13 | 14 | const texture = new TextureLoader().load(dirt); 15 | 16 | const [ref] = useBox(() => ({ 17 | type: 'Static', 18 | ...props 19 | })); 20 | 21 | return ( 22 | { 25 | e.stopPropagation(); 26 | set(Math.floor(e.faceIndex / 2)); 27 | }} 28 | onPointerOut={() => set(null)} 29 | onClick={e => { 30 | e.stopPropagation(); 31 | 32 | const faceIndex = Math.floor(e.faceIndex / 2); 33 | const { x, y, z } = ref.current.position; 34 | 35 | switch (faceIndex) { 36 | case 4: { 37 | addCube(x, y, z + 1); 38 | return; 39 | } 40 | case 2: { 41 | addCube(x, y + 1, z); 42 | return; 43 | } 44 | case 1: { 45 | addCube(x - 1, y, z); 46 | return; 47 | } 48 | case 5: { 49 | addCube(x, y, z - 1); 50 | return; 51 | } 52 | case 3: { 53 | addCube(x, y - 1, z); 54 | return; 55 | } 56 | default: { 57 | addCube(x + 1, y, z); 58 | return; 59 | } 60 | } 61 | }} 62 | > 63 | {[...Array(6)].map((_, index) => ( 64 | 70 | ))} 71 | 72 | 73 | ); 74 | }; 75 | -------------------------------------------------------------------------------- /src/Ground.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { usePlane } from '@react-three/cannon'; 3 | import { TextureLoader, RepeatWrapping } from 'three'; 4 | import grass from './grass.jpg'; 5 | 6 | export const Ground = props => { 7 | const [ref] = usePlane(() => ({ rotation: [-Math.PI / 2, 0, 0], ...props })); 8 | const texture = new TextureLoader().load(grass); 9 | 10 | texture.wrapS = RepeatWrapping; 11 | texture.wrapT = RepeatWrapping; 12 | texture.repeat.set(240, 240); 13 | 14 | return ( 15 | 16 | 17 | 18 | 19 | ); 20 | }; 21 | -------------------------------------------------------------------------------- /src/Player.js: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useRef } from 'react'; 2 | import { useSphere } from '@react-three/cannon'; 3 | import { useThree, useFrame } from 'react-three-fiber'; 4 | import { PointerLockControls } from './PointerLockControls'; 5 | import { usePlayerControls } from './usePlayerControls'; 6 | import { Vector3 } from 'three'; 7 | 8 | const SPEED = 5; 9 | 10 | export const Player = props => { 11 | const { camera } = useThree(); 12 | const { 13 | moveForward, 14 | moveBackward, 15 | moveLeft, 16 | moveRight, 17 | jump 18 | } = usePlayerControls(); 19 | const [ref, api] = useSphere(() => ({ 20 | mass: 1, 21 | type: 'Dynamic', 22 | position: [0, 10, 0], 23 | ...props 24 | })); 25 | 26 | const velocity = useRef([0, 0, 0]); 27 | useEffect(() => { 28 | api.velocity.subscribe(v => (velocity.current = v)); 29 | }, [api.velocity]); 30 | 31 | useFrame(() => { 32 | camera.position.copy(ref.current.position); 33 | const direction = new Vector3(); 34 | 35 | const frontVector = new Vector3( 36 | 0, 37 | 0, 38 | Number(moveBackward) - Number(moveForward) 39 | ); 40 | const sideVector = new Vector3(Number(moveLeft) - Number(moveRight), 0, 0); 41 | 42 | direction 43 | .subVectors(frontVector, sideVector) 44 | .normalize() 45 | .multiplyScalar(SPEED) 46 | .applyEuler(camera.rotation); 47 | 48 | api.velocity.set(direction.x, velocity.current[1], direction.z); 49 | 50 | if (jump && Math.abs(velocity.current[1].toFixed(2)) < 0.05) { 51 | api.velocity.set(velocity.current[0], 10, velocity.current[2]); 52 | } 53 | }); 54 | 55 | return ( 56 | <> 57 | 58 | 59 | 60 | ); 61 | }; 62 | -------------------------------------------------------------------------------- /src/PointerLockControls.js: -------------------------------------------------------------------------------- 1 | import React, { useEffect } from 'react'; 2 | import { PointerLockControls as PointerLockControlsImpl } from 'three/examples/jsm/controls/PointerLockControls'; 3 | import { useThree, extend } from 'react-three-fiber'; 4 | import { useRef } from 'react'; 5 | 6 | extend({ PointerLockControlsImpl }); 7 | 8 | export const PointerLockControls = props => { 9 | const { camera, gl } = useThree(); 10 | const controls = useRef(); 11 | 12 | useEffect(() => { 13 | document.addEventListener('click', () => { 14 | controls.current.lock(); 15 | }); 16 | }, []); 17 | 18 | return ( 19 | 24 | ); 25 | }; 26 | -------------------------------------------------------------------------------- /src/dirt.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/satansdeer/minecraft-react/57810f994f6a3862eedd2e3de88b9a3fc1356557/src/dirt.jpg -------------------------------------------------------------------------------- /src/grass.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/satansdeer/minecraft-react/57810f994f6a3862eedd2e3de88b9a3fc1356557/src/grass.jpg -------------------------------------------------------------------------------- /src/index.css: -------------------------------------------------------------------------------- 1 | * { 2 | box-sizing: border-box; 3 | } 4 | 5 | html, 6 | body, 7 | #root { 8 | width: 100%; 9 | height: 100%; 10 | margin: 0; 11 | padding: 0; 12 | background-color: lightblue; 13 | -webkit-touch-callout: none; 14 | -webkit-user-select: none; 15 | -khtml-user-select: none; 16 | -moz-user-select: none; 17 | -ms-user-select: none; 18 | user-select: none; 19 | overflow: hidden; 20 | } 21 | 22 | body { 23 | position: fixed; 24 | overflow: hidden; 25 | overscroll-behavior-y: none; 26 | font-family: -apple-system, BlinkMacSystemFont, avenir next, avenir, 27 | helvetica neue, helvetica, ubuntu, roboto, noto, segoe ui, arial, sans-serif; 28 | color: black; 29 | } 30 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import React, { StrictMode } from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | 4 | import './index.css'; 5 | import App from './App'; 6 | import * as serviceWorker from './serviceWorker'; 7 | 8 | ReactDOM.render( 9 | 10 | 11 | , 12 | document.getElementById('root') 13 | ); 14 | 15 | // If you want your app to work offline and load faster, you can change 16 | // unregister() to register() below. Note this comes with some pitfalls. 17 | // Learn more about service workers: https://bit.ly/CRA-PWA 18 | serviceWorker.unregister(); 19 | -------------------------------------------------------------------------------- /src/serviceWorker.js: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read https://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.0/8 are considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | export function register(config) { 24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 25 | // The URL constructor is available in all browsers that support SW. 26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 27 | if (publicUrl.origin !== window.location.origin) { 28 | // Our service worker won't work if PUBLIC_URL is on a different origin 29 | // from what our page is served on. This might happen if a CDN is used to 30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 31 | return; 32 | } 33 | 34 | window.addEventListener('load', () => { 35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 36 | 37 | if (isLocalhost) { 38 | // This is running on localhost. Let's check if a service worker still exists or not. 39 | checkValidServiceWorker(swUrl, config); 40 | 41 | // Add some additional logging to localhost, pointing developers to the 42 | // service worker/PWA documentation. 43 | navigator.serviceWorker.ready.then(() => { 44 | console.log( 45 | 'This web app is being served cache-first by a service ' + 46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA' 47 | ); 48 | }); 49 | } else { 50 | // Is not localhost. Just register service worker 51 | registerValidSW(swUrl, config); 52 | } 53 | }); 54 | } 55 | } 56 | 57 | function registerValidSW(swUrl, config) { 58 | navigator.serviceWorker 59 | .register(swUrl) 60 | .then(registration => { 61 | registration.onupdatefound = () => { 62 | const installingWorker = registration.installing; 63 | if (installingWorker == null) { 64 | return; 65 | } 66 | installingWorker.onstatechange = () => { 67 | if (installingWorker.state === 'installed') { 68 | if (navigator.serviceWorker.controller) { 69 | // At this point, the updated precached content has been fetched, 70 | // but the previous service worker will still serve the older 71 | // content until all client tabs are closed. 72 | console.log( 73 | 'New content is available and will be used when all ' + 74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' 75 | ); 76 | 77 | // Execute callback 78 | if (config && config.onUpdate) { 79 | config.onUpdate(registration); 80 | } 81 | } else { 82 | // At this point, everything has been precached. 83 | // It's the perfect time to display a 84 | // "Content is cached for offline use." message. 85 | console.log('Content is cached for offline use.'); 86 | 87 | // Execute callback 88 | if (config && config.onSuccess) { 89 | config.onSuccess(registration); 90 | } 91 | } 92 | } 93 | }; 94 | }; 95 | }) 96 | .catch(error => { 97 | console.error('Error during service worker registration:', error); 98 | }); 99 | } 100 | 101 | function checkValidServiceWorker(swUrl, config) { 102 | // Check if the service worker can be found. If it can't reload the page. 103 | fetch(swUrl, { 104 | headers: { 'Service-Worker': 'script' } 105 | }) 106 | .then(response => { 107 | // Ensure service worker exists, and that we really are getting a JS file. 108 | const contentType = response.headers.get('content-type'); 109 | if ( 110 | response.status === 404 || 111 | (contentType != null && contentType.indexOf('javascript') === -1) 112 | ) { 113 | // No service worker found. Probably a different app. Reload the page. 114 | navigator.serviceWorker.ready.then(registration => { 115 | registration.unregister().then(() => { 116 | window.location.reload(); 117 | }); 118 | }); 119 | } else { 120 | // Service worker found. Proceed as normal. 121 | registerValidSW(swUrl, config); 122 | } 123 | }) 124 | .catch(() => { 125 | console.log( 126 | 'No internet connection found. App is running in offline mode.' 127 | ); 128 | }); 129 | } 130 | 131 | export function unregister() { 132 | if ('serviceWorker' in navigator) { 133 | navigator.serviceWorker.ready 134 | .then(registration => { 135 | registration.unregister(); 136 | }) 137 | .catch(error => { 138 | console.error(error.message); 139 | }); 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /src/setupTests.js: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom/extend-expect'; 6 | -------------------------------------------------------------------------------- /src/state.js: -------------------------------------------------------------------------------- 1 | import { atom } from 'recoil'; 2 | 3 | export const $cubes = atom({ 4 | key: 'cubes', 5 | default: [] 6 | }); 7 | -------------------------------------------------------------------------------- /src/useCubeStore.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { useSetRecoilState, useRecoilValue } from 'recoil'; 3 | import { nanoid } from 'nanoid'; 4 | 5 | import { $cubes } from './state'; 6 | import { Cube } from './Cube'; 7 | 8 | export const useCube = () => useRecoilValue($cubes); 9 | 10 | export const useSetCube = () => { 11 | const setCubes = useSetRecoilState($cubes); 12 | return (x, y, z) => 13 | setCubes(cubes => [...cubes, ]); 14 | }; 15 | -------------------------------------------------------------------------------- /src/usePlayerControls.js: -------------------------------------------------------------------------------- 1 | import { useState, useEffect } from 'react'; 2 | 3 | function moveFieldByKey(key) { 4 | const keys = { 5 | KeyW: 'moveForward', 6 | KeyS: 'moveBackward', 7 | KeyA: 'moveLeft', 8 | KeyD: 'moveRight', 9 | Space: 'jump' 10 | }; 11 | return keys[key]; 12 | } 13 | 14 | export const usePlayerControls = () => { 15 | const [movement, setMovement] = useState({ 16 | moveForward: false, 17 | moveBackward: false, 18 | moveLeft: false, 19 | moveRight: false, 20 | jump: false 21 | }); 22 | 23 | useEffect(() => { 24 | const handleKeyDown = e => { 25 | setMovement(m => ({ 26 | ...m, 27 | [moveFieldByKey(e.code)]: true 28 | })); 29 | }; 30 | const handleKeyUp = e => { 31 | setMovement(m => ({ 32 | ...m, 33 | [moveFieldByKey(e.code)]: false 34 | })); 35 | }; 36 | 37 | document.addEventListener('keydown', handleKeyDown); 38 | document.addEventListener('keyup', handleKeyUp); 39 | 40 | return () => { 41 | document.removeEventListener('keydown', handleKeyDown); 42 | document.removeEventListener('keyup', handleKeyUp); 43 | }; 44 | }, []); 45 | 46 | return movement; 47 | }; 48 | --------------------------------------------------------------------------------