demand

Irregular curved surfaces and track climbing and falling are common requirements in various 3D game projects, especially first-person games.

Results show

Implementation approach

Version: Cocos Creator 3.1

The realization of such requirements can be essentially transformed into: the projection vector of horizontal vector velocity on the landing plane. This process, the Cocos Creator 3.0 API is already provided and we do not need to implement it ourselves.

Implementation steps

  1. With the meshCollider component, the RPG fires a straight down ray

2. Obtain the first intersection point of rays, so that the normal vector of the intersecting plane can be obtained. Vec3. ProjectOnPlane () is used to calculate the velocity component v1 from the plane velocity v0, the normal vector. V1 is the projection of v0 on the plane represented by NorAML

The core code


import { _decorator, Component, Node, geometry, Vec3, v3, PhysicsSystem, director } from 'cc';

const { ccclass, property } = _decorator;

@ccclass('Move')
export class Move extends Component {
    nodeRay: Node = new Node;
    moveAmount: Vec3 = new Vec3();
    speed: number = 3;
    start() {
        this.nodeRay = this.node.getChildByName("nodeRay") as Node;
    }

    update(deltaTime: number) {
        let startPos = this.nodeRay.worldPosition;
        const outRay = new geometry.Ray(startPos.x, startPos.y, startPos.z, 0, -1.0);
        // Default walking direction, here for simplicity do not do keyboard left and right direction control
        let moveDir = v3(-1.0.0).normalize();
        let moveRes = new Vec3(moveDir);
        if (PhysicsSystem.instance.raycast(outRay)) {
            let result = PhysicsSystem.instance.raycastResults[0];
            Vec3.projectOnPlane(moveRes, moveDir, result.hitNormal).normalize();
        }
        this.moveAmount = moveRes.multiplyScalar(this.speed * deltaTime)
    }

    lateUpdate() {
        let originPos = this.node.worldPosition;
        console.debug("moveAmount".this.moveAmount);
        this.node.setPosition(originPos.add(this.moveAmount)); }}Copy the code

summary

The core of irregular terrain walking is to understand the relationship between normal vector of landing point, horizontal plane velocity and slope velocity, and calculate the last parameter according to the first two parameters, so as to calculate displacement. The above is the core of irregular terrain walking, the overall is relatively simple.