To enable moving a chess piece with an animated levitation along a curve to the target square, we need to enhance your existing Three.js chessboard implementation. The following additions include:
- Selection State Management: Track the selected piece and its valid moves.
- Move Execution: Allow the user to click on a valid square to move the selected piece.
- Animation Logic: Animate the piece's movement along a quadratic Bézier curve to the destination square.
Below is the complete code with the necessary enhancements:
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader.js'; // Corrected the path
let chessArray = [
[-4, -2, -3, -5, -6, -3, -2, -4],
[-1, -1, -1, -1, -1, -1, -1, -1],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1],
[4, 2, 3, 5, 6, 3, 2, 4],
];
class ChessSquare {
constructor(id, x, z, material) {
this.id = id;
this.position = { x, z };
this.center = { x: x - 3.5, z: z - 3.5 };
this.invalid = false;
const geometry = new THREE.PlaneGeometry(1, 1);
this.squareMesh = new THREE.Mesh(geometry, material);
this.squareMesh.rotation.x = Math.PI / -2;
this.squareMesh.position.set(this.center.x, 0, this.center.z);
this.squareMesh.userData.id = id
scene.add(this.squareMesh);
}
}
const scene = new THREE.Scene();
const loader = new RGBELoader()
loader.load('./assets/sky/sky.hdr', function(texture) {
texture.mapping = THREE.EquirectangularReflectionMapping;
scene.environment = texture
scene.background = texture
})
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputEncoding = THREE.sRGBEncoding; // Ensure proper color encoding
document.body.appendChild(renderer.domElement);
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.25;
controls.screenSpacePanning = false;
controls.maxPolarAngle = Math.PI / 2;
const blackMaterial = new THREE.MeshBasicMaterial({ color: "#e3c16f" });
const whiteMaterial = new THREE.MeshBasicMaterial({ color: "#b88b4a" });
const chessBoard = [];
const fileLabels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];
const directionalLight = new THREE.DirectionalLight(0xffffff, 4);
directionalLight.position.set(5, 10, 7);
directionalLight.castShadow = true;
scene.add(directionalLight);
class Pawn {
constructor(model_url, position_id, color) {
this.model_url = model_url;
this.position_id = position_id;
this.color = color;
this.isFirstMove = true;
this.pawnMesh = null;
}
loadModel(callback) {
const loader = new GLTFLoader();
loader.load(this.model_url, (gltf) => {
this.pawnMesh = gltf.scene;
const color = this.color === 'white' ? 0xd2b48c : 0x8b4513;
this.pawnMesh.traverse((child) => {
if (child.isMesh) {
child.material = new THREE.MeshToonMaterial({ color: color });
child.userData.parentMesh = this
child.scale.set(0.2, 0.2, 0.2)
}
});
callback(this.pawnMesh);
});
}
valid_moves() {
let letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];
let moves = [];
if (this.color == "white") {
if (this.isFirstMove) {
moves.push(`${this.position_id[0]}${parseInt(this.position_id[1]) - 2}`);
moves.push(`${this.position_id[0]}${parseInt(this.position_id[1]) - 1}`);
} else {
if (parseInt(this.position_id[1]) > 1) {
moves.push(`${this.position_id[0]}${parseInt(this.position_id[1]) - 1}`);
} else {
console.error("Error: Ten ruch jest niemożliwy");
}
}
} else if (this.color == "black") {
if (this.isFirstMove) {
moves.push(`${this.position_id[0]}${parseInt(this.position_id[1]) + 2}`);
moves.push(`${this.position_id[0]}${parseInt(this.position_id[1]) + 1}`);
} else {
if (parseInt(this.position_id[1]) < 8) {
moves.push(`${this.position_id[0]}${parseInt(this.position_id[1]) + 1}`);
} else {
console.error("Error: Ten ruch jest niemożlowy");
}
}
}
return moves;
}
setPosition(x, z) {
if (this.pawnMesh) {
this.pawnMesh.position.set(x - 3.5, 0, z - 3.5);
}
}
onMouseClick() {
const validMoves = this.valid_moves();
console.log('Kliknięto pionka:', this.position_id);
console.log('Możliwe ruchy pionka:', validMoves);
this.highlightValidMoves(validMoves);
return validMoves;
}
highlightValidMoves(validMoves) {
chessBoard.forEach(square => {
const originalMaterial = (square.squareMesh.userData.id.charCodeAt(0) + square.squareMesh.userData.id.charCodeAt(1)) % 2 === 0 ? blackMaterial : whiteMaterial;
square.squareMesh.material = originalMaterial;
});
validMoves.forEach(move => {
const square = chessBoard.find(s => s.squareMesh.userData.id === move);
if (square) {
square.squareMesh.material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
}
});
}
}
class Rook {
constructor(model_url, position_id, color) {
this.model_url = model_url;
this.position_id = position_id;
this.color = color;
this.modelMesh = null;
}
loadModel(callback) {
const loader = new GLTFLoader();
loader.load(this.model_url, (gltf) => {
this.modelMesh = gltf.scene;
const color = this.color === 'white' ? 0xd2b48c : 0x8b4513;
this.modelMesh.traverse((child) => {
if (child.isMesh) {
child.material = new THREE.MeshToonMaterial({ color: color });
child.scale.set(0.2, 0.2, 0.2);
child.userData.parentMesh = this;
}
});
callback(this.modelMesh);
});
}
valid_moves() {
let letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];
let moves = [];
let pos_letter = this.position_id[0];
let pos_num = this.position_id[1];
for (let i = 1; i <= 8; i++) {
let valid_id = `${pos_letter}${i}`;
moves.push(valid_id);
}
for (let i = 0; i < letters.length; i++) {
let valid_id = `${letters[i]}${pos_num}`;
moves.push(valid_id);
}
let filtered_array = moves.filter(item => item !== this.position_id);
return filtered_array;
}
setPosition(x, z) {
if (this.modelMesh) {
this.modelMesh.position.set(x - 3.5, 0, z - 3.5);
}
}
onMouseClick() {
const validMoves = this.valid_moves();
console.log('Kliknięto wieżę:', this.position_id);
console.log('Możliwe ruchy wieży:', validMoves);
this.highlightValidMoves(validMoves);
return validMoves;
}
highlightValidMoves(validMoves) {
chessBoard.forEach(square => {
const originalMaterial = (square.squareMesh.userData.id.charCodeAt(0) + square.squareMesh.userData.id.charCodeAt(1)) % 2 === 0 ? blackMaterial : whiteMaterial;
square.squareMesh.material = originalMaterial;
});
validMoves.forEach(move => {
const square = chessBoard.find(s => s.squareMesh.userData.id === move);
if (square) {
square.squareMesh.material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
}
});
}
}
// Similar classes for Knight, Bishop, Queen, and King with their respective implementations
// ... [Classes Knight, Bishop, Queen, King remain unchanged]
// Initialize chess pieces
let pawn = new Pawn("", "e5", "white");
console.log(pawn.valid_moves());
let blackPawn = new Pawn("", "h4", "black");
console.log(blackPawn.valid_moves());
let rook = new Rook('model', 'd5', 'white');
console.log(rook.valid_moves())
for (let x = 0; x < 8; x++) {
for (let z = 0; z < 8; z++) {
const id = `${fileLabels[x]}${z + 1}`;
const isBlack = (x + z) % 2 === 0;
const material = isBlack ? blackMaterial : whiteMaterial;
const square = new ChessSquare(id, x, z, material);
chessBoard.push(square);
}
}
const pawnModels = [];
function addPawnsToBoard() {
const pawn_model_url = './assets/pawns/pawn/scene.gltf';
const rook_model_url = './assets/pawns/rook/scene.gltf';
const knight_model_url = './assets/pawns/knight/scene.gltf'
const queen_model_url = './assets/pawns/queen/scene.gltf';
const bishop_model_url = './assets/pawns/bishop/scene.gltf'
const king_model_url = './assets/pawns/king/scene.gltf'
for (let x = 0; x < 8; x++) {
for (let z = 0; z < 8; z++) {
const piece = chessArray[z][x];
if (piece == 1 || piece == -1) {
const color = piece > 0 ? 'white' : 'black';
const pawn = new Pawn(pawn_model_url, `${fileLabels[x]}${z + 1}`, color);
pawn.loadModel((mesh) => {
pawn.setPosition(x, z);
scene.add(mesh);
mesh.userData.parentMesh = pawn;
pawnModels.push(mesh);
});
}
if (piece == 2 || piece == -2) {
const color = piece > 0 ? 'white' : 'black';
const knight = new Knight(knight_model_url, `${fileLabels[x]}${z + 1}`, color);
knight.loadModel((mesh) => {
knight.setPosition(x, z);
scene.add(mesh);
mesh.userData.parentMesh = knight;
pawnModels.push(mesh);
});
}
if (piece == 4 || piece == -4) {
const color = piece > 0 ? 'white' : 'black';
const rook = new Rook(rook_model_url, `${fileLabels[x]}${z + 1}`, color);
rook.loadModel((mesh) => {
rook.setPosition(x, z);
scene.add(mesh);
mesh.userData.parentMesh = rook;
pawnModels.push(mesh);
});
}
if (piece == 5 || piece == -5) {
const color = piece > 0 ? 'white' : 'black';
const queen = new Queen(queen_model_url, `${fileLabels[x]}${z + 1}`, color);
queen.loadModel((mesh) => {
queen.setPosition(x, z);
scene.add(mesh);
mesh.userData.parentMesh = queen;
pawnModels.push(mesh);
});
}
if (piece == 3 || piece == -3) {
const color = piece > 0 ? 'white' : 'black';
const bishop = new Bishop(bishop_model_url, `${fileLabels[x]}${z + 1}`, color);
bishop.loadModel((mesh) => {
bishop.setPosition(x, z);
scene.add(mesh);
mesh.userData.parentMesh = bishop;
pawnModels.push(mesh);
});
}
if (piece == 6 || piece == -6) {
const color = piece > 0 ? 'white' : 'black';
const king = new King(king_model_url, `${fileLabels[x]}${z + 1}`, color);
king.loadModel((mesh) => {
king.setPosition(x, z);
scene.add(mesh);
mesh.userData.parentMesh = king;
pawnModels.push(mesh);
});
}
}
}
}
const raycaster = new THREE.Raycaster()
const mouse = new THREE.Vector2()
let selectedPawn = null;
let previousColor = null;
let validMoves = [];
let isAnimating = false; // Flag to prevent actions during animation
// Animation parameters
let animation = {
piece: null,
from: null,
to: null,
startTime: null,
duration: 1000, // in milliseconds
controlPoint: null
};
// Function to compute control point for the quadratic Bézier curve
function computeControlPoint(fromPos, toPos) {
// Mid-point with elevated y for the arc
const midX = (fromPos.x + toPos.x) / 2;
const midZ = (fromPos.z + toPos.z) / 2;
const controlY = 2; // Height of the arc
return new THREE.Vector3(midX, controlY, midZ);
}
window.addEventListener('click', (event) => {
if (isAnimating) return; // Ignore clicks during animation
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
const intersects = raycaster.intersectObjects(pawnModels);
if (selectedPawn && validMoves.length > 0) {
// Check if a square was clicked
const squareIntersects = raycaster.intersectObjects(chessBoard.map(s => s.squareMesh));
if (squareIntersects.length > 0) {
const clickedSquare = squareIntersects[0].object;
const targetId = clickedSquare.userData.id;
if (validMoves.includes(targetId)) {
// Find target square coordinates
const targetSquare = chessBoard.find(s => s.id === targetId);
if (targetSquare) {
const fromId = selectedPawn.userData.parentMesh.position_id;
const toId = targetId;
console.log(`Moving from ${fromId} to ${toId}`);
// Update chessArray
const fromX = fileLabels.indexOf(fromId[0]);
const fromZ = parseInt(fromId[1]) - 1;
const toX = fileLabels.indexOf(toId[0]);
const toZ = parseInt(toId[1]) - 1;
chessArray[toZ][toX] = chessArray[fromZ][fromX];
chessArray[fromZ][fromX] = 0;
// Update piece's new position_id
selectedPawn.userData.parentMesh.position_id = toId;
// Set up animation
animation.piece = selectedPawn.userData.parentMesh;
animation.from = selectedPawn.userData.parentMesh.pawnMesh.position.clone(); // Starting position
animation.to = targetSquare.center.xz ? targetSquare.center.xz : new THREE.Vector3(targetSquare.center.x, 0, targetSquare.center.z);
animation.to = new THREE.Vector3(targetSquare.center.x, 0, targetSquare.center.z);
animation.startTime = performance.now();
animation.controlPoint = computeControlPoint(animation.from, animation.to);
isAnimating = true;
// Reset selection
if (selectedPawn) {
selectedPawn.material.color.set(previousColor);
selectedPawn = null;
}
// Clear valid moves highlighting
chessBoard.forEach(square => {
const originalMaterial = (square.squareMesh.userData.id.charCodeAt(0) + square.squareMesh.userData.id.charCodeAt(1)) % 2 === 0 ? blackMaterial : whiteMaterial;
square.squareMesh.material = originalMaterial;
});
}
} else {
// Clicked square is not a valid move, deselect
if (selectedPawn) {
selectedPawn.material.color.set(previousColor);
selectedPawn = null;
}
chessBoard.forEach(square => {
const originalMaterial = (square.squareMesh.userData.id.charCodeAt(0) + square.squareMesh.userData.id.charCodeAt(1)) % 2 === 0 ? blackMaterial : whiteMaterial;
square.squareMesh.material = originalMaterial;
});
}
}
}
if (!selectedPawn) {
if (intersects.length > 0) {
const clickedObject = intersects[0].object;
const selectedPiece = clickedObject.userData.parentMesh;
console.log('Kliknięto obiekt:', clickedObject);
console.log('selectedPiece:', selectedPiece);
if (selectedPiece && typeof selectedPiece.onMouseClick === 'function') {
validMoves = selectedPiece.onMouseClick();
} else {
console.error("Error: Kliknięty obiekt nie jest figurą lub nie ma metody onMouseClick");
}
if (selectedPawn) {
selectedPawn.material.color.set(previousColor);
}
previousColor = clickedObject.material.color.getHex();
clickedObject.material.color.set(0xFFD700);
selectedPawn = clickedObject;
}
}
});
addPawnsToBoard();
camera.position.set(5, 10, 5); // Adjusted camera height for better view
controls.update();
function animate() {
controls.update();
renderer.render(scene, camera);
// Handle animation
if (animation.piece) {
const currentTime = performance.now();
const elapsed = currentTime - animation.startTime;
const t = Math.min(elapsed / animation.duration, 1); // Clamp t to [0,1]
// Quadratic Bézier curve
const pos = computeQuadraticBezierPoint(t, animation.from, animation.controlPoint, animation.to);
// Update piece position
animation.piece.setPosition((pos.x + 3.5), (pos.z + 3.5)); // Adjusting back to grid coordinates
if (animation.piece.pawnMesh) {
animation.piece.pawnMesh.position.copy(pos);
} else if (animation.piece.modelMesh) {
animation.piece.modelMesh.position.copy(pos);
}
if (t >= 1) {
// Animation complete
animation.piece.setPosition(
fileLabels.indexOf(animation.piece.position_id[0]),
parseInt(animation.piece.position_id[1]) - 1
);
animation.piece = null;
isAnimating = false;
}
}
requestAnimationFrame(animate);
}
animate();
// Function to compute a point on a quadratic Bézier curve
function computeQuadraticBezierPoint(t, p0, p1, p2) {
const oneMinusT = 1 - t;
const x = oneMinusT * oneMinusT * p0.x + 2 * oneMinusT * t * p1.x + t * t * p2.x;
const y = oneMinusT * oneMinusT * p0.y + 2 * oneMinusT * t * p1.y + t * t * p2.y;
const z = oneMinusT * oneMinusT * p0.z + 2 * oneMinusT * t * p1.z + t * t * p2.z;
return new THREE.Vector3(x, y, z);
}
Explanation of Additions
-
Selection State Management:
- Variables:
selectedPawn: Tracks the currently selected piece.
validMoves: Stores the valid moves of the selected piece.
isAnimating: A flag to prevent interactions during animation.
- Click Handling:
- If a piece is selected and a valid square is clicked, the move is executed.
- If no piece is selected, clicking on a piece selects it and highlights its valid moves.
-
Move Execution:
- Updating
chessArray:
- Moves are reflected in the
chessArray to keep the state consistent.
- Updating Piece's
position_id:
- The piece's
position_id is updated to the new location.
- Deselection and Highlight Clearing:
- After a move is made, the selection and highlighting are cleared.
-
Animation Logic:
- Animation Object:
- Stores the piece to animate, start and end positions, start time, duration, and control point for the Bézier curve.
- Computing the Control Point:
- The
computeControlPoint function calculates a midpoint elevated along the Y-axis to create an arc.
- Animating in the
animate Function:
- During each frame, if an animation is active, the piece's position is updated based on the Bézier curve.
- The animation progresses by increasing the parameter
t from 0 to 1 over the specified duration.
- Once the animation completes (
t >= 1), the piece's position is finalized, and the animation state is reset.
-
Utility Function:
computeQuadraticBezierPoint: Calculates a point on a quadratic Bézier curve given a parameter t and three control points (p0, p1, p2).
-
Camera Adjustment:
Additional Notes
With these additions, your chess pieces should now move with a smooth levitation animation along a curved path to the selected square, enhancing the visual interactivity of your chessboard.