JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdn.jsdelivr.net/npm/three@0.115.0/build/three.min.js"></script>
CSS
body {
margin: 0;
padding: 0;
width: 100vw;
height: 100vh;
overflow: hidden;
}
TypeScript
const PLAYER_SIZE = 10
const PLAYER_HEIGHT = 20
function createPlayer() {
var obj = new THREE.Group()
// this.obj.up = new THREE.Vector3(0, 0, 1)
const body = new THREE.Mesh(
new THREE.CylinderGeometry(PLAYER_SIZE/2, PLAYER_SIZE/2, PLAYER_HEIGHT, 30),
new THREE.MeshPhongMaterial({color: 0xffffff, flatShading: true})
)
body.rotateX(Math.PI / 2);
// body.rotation.x = Math.PI/2
// body.position.z = PLAYER_HEIGHT/2
obj.add(body)
const SPEAR_LENGTH = 40
const spear = new THREE.Group()
const shaft = new THREE.Mesh(
new THREE.BoxBufferGeometry(1, 40, 1),
new THREE.MeshPhongMaterial({color: 0xa52a2a, flatShading: true})
)
spear.add(shaft)
const head = new THREE.Mesh(
new THREE.CylinderGeometry(0, 2, 5, 10),
new THREE.MeshPhongMaterial({color: 0xc0c0c0, flatShading: true})
)
head.position.y = SPEAR_LENGTH/2
spear.add(head)
spear.position.x = PLAYER_SIZE/2
spear.position.y = PLAYER_SIZE
// spear.position.z = PLAYER_HEIGHT/2
obj.add(spear)
return obj
}
function getWorldPosFromScreenPos(screenPosition: THREE.Vector2): THREE.Vector2 {
const rayCaster = new THREE.Raycaster()
rayCaster.setFromCamera(screenPosition, camera)
const plane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0)
const intersectPoint = new THREE.Vector3()
rayCaster.ray.intersectPlane(plane, intersectPoint)
return new THREE.Vector2(intersectPoint.x, intersectPoint.y)
}
const start = new Date().getTime()
function tick(renderer: any, mousePosition: THREE.Vector2): void {
const mouseWorldPos = getWorldPosFromScreenPos(mousePosition)
if (new Date().getTime() - start > 1000) { // start looking at the mouse after 1 second
player.lookAt(mouseWorldPos.x, mouseWorldPos.y, 0)
}
renderer.render(scene, camera)
}
var renderer = new THREE.WebGLRenderer({alpha: true, antialias: true})
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)
var canvas = renderer.domElement
var mousePosition = new THREE.Vector2(0,...