DEV Community

Cover image for TCJSGame Movement Utilities: Complete Reference Guide
Kehinde Owolabi
Kehinde Owolabi

Posted on

TCJSGame Movement Utilities: Complete Reference Guide

TCJSGame Movement Utilities: Complete Reference Guide

Game Movement Mechanics

Introduction to Movement Utilities

TCJSGame provides a comprehensive set of movement utilities through the move object that simplify complex game mechanics. These utilities handle everything from basic positioning to advanced physics-based movements.

🎯 Basic Movement Functions

Direct Positioning

// Instant teleportation to coordinates
move.teleport(player, 300, 200);

// Set individual coordinates
move.setX(player, 150);  // Set X position only
move.setY(player, 250);  // Set Y position only

// Example: Reset player position
function resetPlayer() {
    move.teleport(player, 100, 100);
}
Enter fullscreen mode Exit fullscreen mode

Screen Positioning

// Position components relative to screen edges
move.position(player, "center");        // Center of screen
move.position(player, "top", 20);       // 20px from top
move.position(player, "bottom", 10);    // 10px from bottom  
move.position(player, "left", 30);      // 30px from left
move.position(player, "right", 40);     // 40px from right

// Example: Create UI elements
const scoreText = new Component(20, 20, "white", 0, 0, "text");
move.position(scoreText, "top", 10);
move.position(scoreText, "left", 10);
Enter fullscreen mode Exit fullscreen mode

🚀 Physics-Based Movement

Basic Physics Movement

// Enable physics and move with forces
move.backward(player, 2);  // Move with physics enabled

// Manual physics control
player.physics = true;
player.gravity = 0.5;
player.bounce = 0.7;
player.speedX = 3;
player.speedY = -5;
Enter fullscreen mode Exit fullscreen mode

Acceleration and Deceleration

// Accelerate with optional maximum speed
move.accelerate(player, 0.1, 0, 5);     // X acceleration, max speed 5
move.accelerate(player, 0, 0.2, 10);    // Y acceleration, max speed 10

// Decelerate (friction)
move.decelerate(player, 0.2, 0.1);      // X decel: 0.2, Y decel: 0.1

// Example: Car-like movement
function update() {
    if (display.keys[37]) { // Left
        move.accelerate(car, -0.2, 0, 8);
    }
    if (display.keys[39]) { // Right
        move.accelerate(car, 0.2, 0, 8);
    }
    // Automatic deceleration when no key pressed
    if (!display.keys[37] && !display.keys[39]) {
        move.decelerate(car, 0.1, 0);
    }
}
Enter fullscreen mode Exit fullscreen mode

✨ Smooth Movement Effects

Glide Movements (Smooth Easing)

// Glide horizontally over time
move.glideX(player, 2, 400);    // Glide to X=400 over 2 seconds

// Glide vertically over time  
move.glideY(player, 1.5, 300);  // Glide to Y=300 over 1.5 seconds

// Glide to specific coordinates
move.glideTo(player, 2, 400, 300);  // Glide to (400,300) over 2 seconds

// Example: Smooth camera transitions
function moveCameraTo(x, y) {
    move.glideTo(display.camera, 1.5, x, y);
}
Enter fullscreen mode Exit fullscreen mode

Projectile Motion

// Realistic projectile physics in one function call
move.project(player, 15, 45, 0.1);  // Velocity, angle, gravity

// Parameter breakdown:
// - initialVelocity: Launch speed (15)
// - angle: Launch angle in degrees (45°)
// - gravity: Gravity strength (0.1)

// Example: Cannon firing
function fireCannon() {
    move.project(cannonBall, 20, 30, 0.2);
}
Enter fullscreen mode Exit fullscreen mode

🎪 Advanced Movement Patterns

Circular Movement

// Create circular/orbital movement
move.circle(player, 2);  // Rotate at 2 degrees per frame

// Example: Planetary orbits
move.circle(planet, 0.5);    // Slow orbit
move.circle(moon, 3);        // Fast orbit around planet
Enter fullscreen mode Exit fullscreen mode

Rotation and Direction

// Rotate component (in degrees)
move.turnLeft(player, 5);   // Rotate 5 degrees counter-clockwise
move.turnRight(player, 5);  // Rotate 5 degrees clockwise

// Point toward a target
move.pointTo(player, enemy.x, enemy.y);      // Face enemy
move.pointTo(bullet, targetX, targetY);      // Aim bullet

// Example: Turret tracking
function update() {
    move.pointTo(turret, mouse.x, mouse.y);
}
Enter fullscreen mode Exit fullscreen mode

🛡️ Boundary and Constraint System

Screen Boundaries

// Keep within canvas bounds automatically
move.bound(player);

// Example: Prevent player from leaving screen
function update() {
    move.bound(player);
}
Enter fullscreen mode Exit fullscreen mode

Custom Boundaries

// Define custom boundaries
move.boundTo(player, 0, 700, 0, 500);  // left, right, top, bottom

// Partial boundaries (only constrain specific sides)
move.boundTo(player, 0, false, 100, false);  // Only left constraint
move.boundTo(player, false, 800, false, 400); // Only right and bottom

// Example: Platform game boundaries
move.boundTo(player, 0, 2000, 0, false);  // Horizontal scrolling limits
Enter fullscreen mode Exit fullscreen mode

Collision-Based Movement

// Basic object collision response
move.hitObject(player, platform);

// Example: Platform collision
function update() {
    if (player.crashWith(platform)) {
        move.hitObject(player, platform);
    }
}
Enter fullscreen mode Exit fullscreen mode

🎮 Object Management Utilities

Object Cloning (Stamping)

// Create copies of components
const bullet = move.stamp(player);  // Clone player properties
bullet.width = 10;
bullet.height = 10;
display.add(bullet);

// Remove stamped objects
move.clearStamp(bullet);  // Stop rendering the stamp

// Example: Bullet firing system
function fireBullet() {
    const newBullet = move.stamp(bulletTemplate);
    move.teleport(newBullet, player.x, player.y);
    move.project(newBullet, 10, 0, 0.1);
    display.add(newBullet);
    bullets.push(newBullet);
}
Enter fullscreen mode Exit fullscreen mode

Visual Effects

// Create visual dots (debugging)
move.dot(player);  // Draw a dot at player's position

// Example: Trail effect
function createTrail() {
    const trailDot = new Component(3, 3, "red", player.x, player.y, "rect");
    move.dot(trailDot);
    setTimeout(() => move.clearStamp(trailDot), 1000);
}
Enter fullscreen mode Exit fullscreen mode

🎯 Practical Game Examples

Platformer Character Controller

const player = new Component(30, 30, "blue", 100, 100, "rect");
player.physics = true;
player.gravity = 0.5;
player.bounce = 0.2;

function update() {
    // Horizontal movement
    if (display.keys[37]) { // Left
        move.accelerate(player, -0.3, 0, 5);
    } else if (display.keys[39]) { // Right
        move.accelerate(player, 0.3, 0, 5);
    } else {
        move.decelerate(player, 0.2, 0);
    }

    // Jumping
    if (display.keys[38] && player.gravitySpeed === 0) {
        move.accelerate(player, 0, -12, 15);
    }

    // Screen boundaries
    move.boundTo(player, 0, display.canvas.width, 0, false);
}
Enter fullscreen mode Exit fullscreen mode

Top-Down Shooter Movement

const spaceship = new Component(40, 40, "red", 400, 300, "rect");

function update() {
    // Keyboard movement
    if (display.keys[87]) move.accelerate(spaceship, 0, -0.2, 8);  // W - Up
    if (display.keys[83]) move.accelerate(spaceship, 0, 0.2, 8);   // S - Down
    if (display.keys[65]) move.accelerate(spaceship, -0.2, 0, 8);  // A - Left
    if (display.keys[68]) move.accelerate(spaceship, 0.2, 0, 8);   // D - Right

    // Automatic deceleration
    if (!display.keys[87] && !display.keys[83]) move.decelerate(spaceship, 0, 0.1);
    if (!display.keys[65] && !display.keys[68]) move.decelerate(spaceship, 0.1, 0);

    // Point toward mouse
    move.pointTo(spaceship, mouse.x, mouse.y);

    // Screen wrapping
    if (spaceship.x < -spaceship.width) spaceship.x = display.canvas.width;
    if (spaceship.x > display.canvas.width) spaceship.x = -spaceship.width;
    if (spaceship.y < -spaceship.height) spaceship.y = display.canvas.height;
    if (spaceship.y > display.canvas.height) spaceship.y = -spaceship.height;
}
Enter fullscreen mode Exit fullscreen mode

Puzzle Game Piece Movement

const puzzlePiece = new Component(50, 50, "yellow", 200, 200, "rect");

function movePieceToSlot(slotX, slotY) {
    // Smooth movement to slot position
    move.glideTo(puzzlePiece, 0.5, slotX, slotY);
}

// Example grid-based movement
const gridSize = 50;
function movePiece(direction) {
    let targetX = puzzlePiece.x;
    let targetY = puzzlePiece.y;

    switch(direction) {
        case 'up': targetY -= gridSize; break;
        case 'down': targetY += gridSize; break;
        case 'left': targetX -= gridSize; break;
        case 'right': targetX += gridSize; break;
    }

    move.glideTo(puzzlePiece, 0.3, targetX, targetY);
}
Enter fullscreen mode Exit fullscreen mode

🔧 Advanced Movement Patterns

Patrol Movement AI

const enemy = new Component(30, 30, "red", 100, 100, "rect");
let patrolPoints = [{x: 100, y: 100}, {x: 400, y: 100}, {x: 400, y: 300}];
let currentPoint = 0;
let isMoving = false;

function update() {
    if (!isMoving) {
        const target = patrolPoints[currentPoint];
        move.glideTo(enemy, 2, target.x, target.y);
        isMoving = true;

        setTimeout(() => {
            currentPoint = (currentPoint + 1) % patrolPoints.length;
            isMoving = false;
        }, 2000);
    }
}
Enter fullscreen mode Exit fullscreen mode

Homing Missile Behavior

const missile = new Component(10, 20, "orange", 100, 100, "rect");
const target = new Component(30, 30, "blue", 500, 300, "rect");

function update() {
    // Point toward target
    move.pointTo(missile, target.x, target.y);

    // Move forward in the direction it's facing
    const speed = 3;
    missile.x += Math.cos(missile.angle) * speed;
    missile.y += Math.sin(missile.angle) * speed;

    // Homing effect - adjust angle slightly toward target
    const targetAngle = Math.atan2(target.y - missile.y, target.x - missile.x);
    const angleDiff = targetAngle - missile.angle;
    missile.angle += angleDiff * 0.1; // 10% correction per frame
}
Enter fullscreen mode Exit fullscreen mode

⚡ Performance Optimization

Efficient Movement Patterns

// Use object pooling for frequently moving objects
const bulletPool = [];

function getBullet() {
    for (let bullet of bulletPool) {
        if (!bullet.active) {
            bullet.active = true;
            return bullet;
        }
    }
    // Create new bullet if pool is empty
    const newBullet = new Component(5, 5, "yellow", 0, 0, "rect");
    newBullet.active = true;
    bulletPool.push(newBullet);
    return newBullet;
}

function recycleBullet(bullet) {
    bullet.active = false;
    move.teleport(bullet, -100, -100); // Move offscreen
}
Enter fullscreen mode Exit fullscreen mode

Movement State Management

// Use movement states to optimize updates
const movementStates = {
    IDLE: 0,
    MOVING: 1,
    JUMPING: 2,
    FALLING: 3
};

let playerState = movementStates.IDLE;

function update() {
    switch(playerState) {
        case movementStates.IDLE:
            handleIdleState();
            break;
        case movementStates.MOVING:
            handleMovingState();
            break;
        case movementStates.JUMPING:
            handleJumpingState();
            break;
        case movementStates.FALLING:
            handleFallingState();
            break;
    }
}
Enter fullscreen mode Exit fullscreen mode

🐛 Common Issues and Solutions

Movement Not Working

// Ensure physics is enabled for certain movements
player.physics = true;  // Required for physics-based movements

// Check if component is properly added to display
display.add(player);

// Verify speed values are being set
console.log("Player speed:", player.speedX, player.speedY);
Enter fullscreen mode Exit fullscreen mode

Smooth Movement Stuttering

// Use requestAnimationFrame for smoother movements
function smoothGlide(component, targetX, targetY, duration) {
    const startX = component.x;
    const startY = component.y;
    const startTime = performance.now();

    function animate(currentTime) {
        const elapsed = currentTime - startTime;
        const progress = Math.min(elapsed / duration, 1);

        component.x = startX + (targetX - startX) * progress;
        component.y = startY + (targetY - startY) * progress;

        if (progress < 1) {
            requestAnimationFrame(animate);
        }
    }
    requestAnimationFrame(animate);
}
Enter fullscreen mode Exit fullscreen mode

📚 Conclusion

TCJSGame's movement utilities provide:

  • Simple API for common game movements
  • Physics integration for realistic motion
  • Smooth animations with glide functions
  • Advanced patterns for complex behaviors
  • Boundary management for game world constraints

These utilities dramatically reduce the code needed for complex movement systems, allowing developers to focus on game design rather than physics implementation.

For more advanced movement patterns and real-time examples, visit the official TCJSGame documentation and experiment with different combinations of these powerful utilities!

Top comments (0)