Skip to content
AdvancedVehicle

Gameplay / AdvancedVehicle

AdvancedVehicle Class

Four-wheel vehicle

Four wheel vehicles refer to vehicles simulating four wheels, such as cars, trucks, etc. They are designed to move, accelerate and turn freely in the game, giving Player a real driving experience.

Precautions

Important Notes

  1. Before the effective owner is set, the vehicle will not carry out physical simulation, and may encounter suspended phenomena.
  2. The vehicle is control by the Player client specified during the set owner. If you want to set the position of the vehicle, setting the position only on the server side is invalid and needs to be modified together with the main control end.
  3. Attention should be paid to the number of vehicles controlled simultaneously by the same client. If the number is too large, it will affect the synchronization of the vehicles. Suggest within 5.

Usage example: Dynamically create vehicles through scripts and bind control logic. Create a script named 'VehicleExample', place it in the object bar, open the script, enter the following code to save, and run the game. Press the Q key to create the vehicle, and when it reaches the trigger range, it will automatically get on board. WASD will drive it, and press the F key to get off. The code is as follows:

ts
enum VehicleEvents {
    createVehicle_C2S = "createVehicle_C2S",
    createVehicle_S2C = "createVehicle_S2C",
    outOfVehicle_local = "outOfVehicle_local",
}

@Component
export default class VehicleSample extends Script {

    // The property is exposed in the property panel and can be easily adjust.
    @Property({ displayName: "Vehicle generate position", hideInEditor: false })
    private vehicleSpawnLoc: Vector = new Vector(100, 100, 200);

    // The currently controlled vehicle.
    private vehicle: AdvancedVehicle = null;

    // The interaction object under the current vehicle.
    private interactor: Interactor = null;

    // The trigger under the current vehicle is used for getting on and off the vehicle.
    private trigger: Trigger = null;

    // The currently bound button event handle is used to unbind when getting off the vehicle.
    private controlEventsHandle: mw.EventListener[] = [];

    // When the script is instanced, this function will be call before the first frame update.
    protected onStart(): void {
        AssetUtil.asyncDownloadAsset("14015");

        this.bindCreationEvents();
    }

    // Bind the event create by vehicle
    private bindCreationEvents(): void {
        if (SystemUtil.isServer()) {
            mw.Event.addClientListener(VehicleEvents.createVehicle_C2S, async (player: Player) => {
                // Create a vehicle.
                this.vehicle = await mw.GameObject.asyncSpawn<mw.AdvancedVehicle> ("Vehicle4W", {
                    replicates: true,
                    transform: new Transform(this.vehicleSpawnLoc, new Rotation(0, 0, 0), new Vector(1)),
                })

                // Create a Trigger.
                this.trigger = await mw.GameObject.asyncSpawn<mw.Trigger> ("Trigger", {
                    replicates: true,
                })

                // Create interactor.
                this.interactor = await mw.GameObject.asyncSpawn<mw.Interactor>("Interactor", {
                    replicates: true,
                })

                // Create a Box as the body.
                const vehicleMesh = await mw.GameObject.asyncSpawn<mw.Model>("197386", {
                    replicates: true,
                })

                // Set parent-child relationship.
                this.interactor.parent = this.vehicle;
                this.trigger.parent = this.vehicle;
                vehicleMesh.parent = this.vehicle;

                // Adjust the relative position so that the player sits exactly on the Box when getting on the car and next to the trigger when getting off the car.
                this.interactor.localTransform.position = new mw.Vector(0, 0, 150);
                this.trigger.localTransform.position = new mw.Vector(0, -100, 0);
                vehicleMesh.localTransform.position= new mw.Vector(0, 0, 50);

                // Notify the requesting client that the vehicle has been create. Because we only notified the client that initiated the request, each client can only drive the vehicle that it requested to create create.
                mw.Event.dispatchToClient(player, VehicleEvents.createVehicle_S2C, [
                    this.vehicle.gameObjectId,
                    this.trigger.gameObjectId,
                    this.interactor.gameObjectId,
                ])
            })
        } else {
            InputUtil.onKeyDown(Keys.Q, () => {
                // Dynamically generate vehicle, Trigger and interactor on the server through RPC call.
                mw.Event.dispatchToServer(VehicleEvents.createVehicle_C2S);
            })

            // The client listens to the message generated by the server, binds the trigger event, and implements the boarding and alighting function.
            mw.Event.addServerListener(VehicleEvents.createVehicle_S2C, async (info: string[]) => {
                const [vehicleGUID, triggerGUID, interactorGUID] = info;
                console.log(`vehicleGUID = [${vehicleGUID}], triggerGUID = [${triggerGUID}], interactorGUID = [${interactorGUID}]`);

                this.vehicle = await GameObject.asyncFindGameObjectById(vehicleGUID) as AdvancedVehicle;
                this.trigger = await GameObject.asyncFindGameObjectById(triggerGUID) as Trigger;
                this.interactor = await GameObject.asyncFindGameObjectById(interactorGUID) as Interactor;

                this.bindInOutVehicleEvents();
            })
        }
    }

    // Bind trigger events to achieve boarding and alighting functions.
    private bindInOutVehicleEvents(): void {
        // Automatically board the vehicle through a trigger
        this.trigger.onEnter.add(async (chara: Character) => {
            // Determine if it is a trigger triggered by the player character's touch and if it is the current player.
            if (chara && chara.player == await mw.Player.asyncGetLocalPlayer()) {
                // Close character collisions to avoid interaction with vehicles.
                chara.setCollision(CollisionStatus.Off);
                // Activate the interactor and let the character sit on the car.
                this.interactor.enter(chara, mw.HumanoidSlotType.Buttocks, "14015");
                // Set the driver of the vehicle, and then start to simulate physics and drive.
                this.vehicle.owner = chara.player;
                // Adjust some parameters.
                const handle_press_one = InputUtil.onKeyDown(Keys.One, () => {
                    // Press 1 adjust the vehicle mass
                    this.adjustVehicleMass();
                });
                this.controlEventsHandle.push(handle_press_one);

                const handle_press_two = InputUtil.onKeyDown(Keys.Two, () => {
                    // Press 2 adjust the friction coefficient of vehicle
                    this.adjustVehicleFriction();
                });
                this.controlEventsHandle.push(handle_press_two);

                const handle_press_three = InputUtil.onKeyDown(Keys.Three, () => {
                    // Press 3 adjust the maximum engine speed of vehicle
                    this.adjustVehicleMaxEngineRPM();
                });
                this.controlEventsHandle.push(handle_press_three);

                const handle_press_four = InputUtil.onKeyDown(Keys.Four, () => {
                    // Press 4 adjust vehicle acceleration
                    this.adjustVehicleAcceleration();
                });
                this.controlEventsHandle.push(handle_press_four);

                const handle_press_five = InputUtil.onKeyDown(Keys.Five, () => {
                    // Press 5 to adjust the braking torque of the vehicle
                    this.adjustVehicleBrakingTorque();
                });
                this.controlEventsHandle.push(handle_press_five);

                this.VehicleKeyEvents();
            }
        })

        // Monitor the incident of getting off the car.
        mw.Event.addLocalListener(VehicleEvents.outOfVehicle_local, async () => {
            const player = await Player.asyncGetLocalPlayer();
            // Set the exit position to the left of the Trigger.
            const outOfVehicleLoc = this.trigger.worldTransform.position.add(new Vector(0, -100, 50));
            // The interaction ends and the character gets off.
            this.interactor.leave(outOfVehicleLoc);
            // Enable character collision to avoid falling to the ground and other incorrect collisions.
            player.character.setCollision(CollisionStatus.On);
            // Empty the driver of the vehicle. At this time, physics will still be simulated, but control cannot continue.
            this.vehicle.owner = null;

            this.clearControlEvents();
        })
    }

    // Control the movement of the vehicle through buttons.
    private VehicleKeyEvents() {
        this.clearControlEvents();

        //Press the UP button to refuel the vehicle and move forward;
        const handle_up_1 = InputUtil.onKeyDown(Keys.W, () => {
            this.vehicle.throttleInput = 1;
        });
        const handle_up_0 = InputUtil.onKeyUp(Keys.W, () => {
            this.vehicle.throttleInput = 0;
        });
        this.controlEventsHandle.push(handle_up_1, handle_up_0);

        //Press Down to slow down the vehicle;
        const handle_down_1 = InputUtil.onKeyDown(Keys.S, () => {
            this.vehicle.throttleInput = -1;
        });
        const handle_down_0 = InputUtil.onKeyUp(Keys.S, () => {
            this.vehicle.throttleInput = 0;
        });
        this.controlEventsHandle.push(handle_down_1, handle_down_0);

        //Press LEFT to turn the vehicle left;
        const handle_left_1 = InputUtil.onKeyDown(Keys.A, () => {
            this.vehicle.steeringInput = -1;
        });
        const handle_left_0 = InputUtil.onKeyUp(Keys.A, () => {
            this.vehicle.steeringInput = 0;
        });
        this.controlEventsHandle.push(handle_left_1, handle_left_0);

        //Press the RIGHT key to make the vehicle turn right;
        const handle_right_1 = InputUtil.onKeyDown(Keys.D, () => {
            this.vehicle.steeringInput = 1;
        });
        const handle_right_0 = InputUtil.onKeyUp(Keys.D, () => {
            this.vehicle.steeringInput = 0;
        });
        this.controlEventsHandle.push(handle_right_1, handle_right_0);

        //Press the SpaceBar button to brake the vehicle;
        const handle_spaceBar_1 = InputUtil.onKeyDown(Keys.SpaceBar, () => {
            this.vehicle.handbrakeInputEnable = true;
        });
        const handle_spaceBar_0 = InputUtil.onKeyUp(Keys.SpaceBar, () => {
            this.vehicle.handbrakeInputEnable = false;
        });
        this.controlEventsHandle.push(handle_spaceBar_1, handle_spaceBar_0);

        //Press key F to get out.
        const handle_f = InputUtil.onKeyDown(Keys.F, () => {
            mw.Event.dispatchToLocal(VehicleEvents.outOfVehicle_local);
        });
        this.controlEventsHandle.push(handle_f);
    }

    // Unbind button event.
    private clearControlEvents(): void {
        for (const handle of this.controlEventsHandle) {
            handle.isConnected && handle.disconnect();
        }

        this.controlEventsHandle = [];
    }

    // Adjust the mass of vehicle (1500 and 10000 switch back and forth).
    private adjustVehicleMass(): void {
        if (this.vehicle.mass == 1500) {
            this.vehicle.mass = 10000;
        } else {
            this.vehicle.mass = 1500;
        }
    }

    // Adjust the friction coefficient of vehicle (switch back and forth between 0.01 and 3).
    private adjustVehicleFriction(): void {
        if (this.vehicle.friction == 3) {
            this.vehicle.friction = 0.01;
        } else {
            this.vehicle.friction = 3;
        }
    }

    // Adjust the maximum speed of vehicle engine (1000 and 6000 switch back and forth).
    private adjustVehicleMaxEngineRPM(): void {
        if (this.vehicle.maxEngineRPM == 6000) {
            this.vehicle.maxEngineRPM = 1000;
        } else {
            this.vehicle.maxEngineRPM = 6000;
        }
    }

    // Adjust the acceleration of vehicle (switch back and forth between 0.1 and 1).
    private adjustVehicleAcceleration(): void {
        if (this.vehicle.acceleration == 1) {
            this.vehicle.acceleration = 0.1;
        } else {
            this.vehicle.acceleration = 1;
        }
    }

    // Adjust the brake torque of vehicle (switch back and forth between 0 and 1500).
    private adjustVehicleBrakingTorque(): void {
        if (this.vehicle.brakingTorque == 1500) {
            this.vehicle.brakingTorque = 0;
        } else {
            this.vehicle.brakingTorque = 1500;
        }
    }
}
enum VehicleEvents {
    createVehicle_C2S = "createVehicle_C2S",
    createVehicle_S2C = "createVehicle_S2C",
    outOfVehicle_local = "outOfVehicle_local",
}

@Component
export default class VehicleSample extends Script {

    // The property is exposed in the property panel and can be easily adjust.
    @Property({ displayName: "Vehicle generate position", hideInEditor: false })
    private vehicleSpawnLoc: Vector = new Vector(100, 100, 200);

    // The currently controlled vehicle.
    private vehicle: AdvancedVehicle = null;

    // The interaction object under the current vehicle.
    private interactor: Interactor = null;

    // The trigger under the current vehicle is used for getting on and off the vehicle.
    private trigger: Trigger = null;

    // The currently bound button event handle is used to unbind when getting off the vehicle.
    private controlEventsHandle: mw.EventListener[] = [];

    // When the script is instanced, this function will be call before the first frame update.
    protected onStart(): void {
        AssetUtil.asyncDownloadAsset("14015");

        this.bindCreationEvents();
    }

    // Bind the event create by vehicle
    private bindCreationEvents(): void {
        if (SystemUtil.isServer()) {
            mw.Event.addClientListener(VehicleEvents.createVehicle_C2S, async (player: Player) => {
                // Create a vehicle.
                this.vehicle = await mw.GameObject.asyncSpawn<mw.AdvancedVehicle> ("Vehicle4W", {
                    replicates: true,
                    transform: new Transform(this.vehicleSpawnLoc, new Rotation(0, 0, 0), new Vector(1)),
                })

                // Create a Trigger.
                this.trigger = await mw.GameObject.asyncSpawn<mw.Trigger> ("Trigger", {
                    replicates: true,
                })

                // Create interactor.
                this.interactor = await mw.GameObject.asyncSpawn<mw.Interactor>("Interactor", {
                    replicates: true,
                })

                // Create a Box as the body.
                const vehicleMesh = await mw.GameObject.asyncSpawn<mw.Model>("197386", {
                    replicates: true,
                })

                // Set parent-child relationship.
                this.interactor.parent = this.vehicle;
                this.trigger.parent = this.vehicle;
                vehicleMesh.parent = this.vehicle;

                // Adjust the relative position so that the player sits exactly on the Box when getting on the car and next to the trigger when getting off the car.
                this.interactor.localTransform.position = new mw.Vector(0, 0, 150);
                this.trigger.localTransform.position = new mw.Vector(0, -100, 0);
                vehicleMesh.localTransform.position= new mw.Vector(0, 0, 50);

                // Notify the requesting client that the vehicle has been create. Because we only notified the client that initiated the request, each client can only drive the vehicle that it requested to create create.
                mw.Event.dispatchToClient(player, VehicleEvents.createVehicle_S2C, [
                    this.vehicle.gameObjectId,
                    this.trigger.gameObjectId,
                    this.interactor.gameObjectId,
                ])
            })
        } else {
            InputUtil.onKeyDown(Keys.Q, () => {
                // Dynamically generate vehicle, Trigger and interactor on the server through RPC call.
                mw.Event.dispatchToServer(VehicleEvents.createVehicle_C2S);
            })

            // The client listens to the message generated by the server, binds the trigger event, and implements the boarding and alighting function.
            mw.Event.addServerListener(VehicleEvents.createVehicle_S2C, async (info: string[]) => {
                const [vehicleGUID, triggerGUID, interactorGUID] = info;
                console.log(`vehicleGUID = [${vehicleGUID}], triggerGUID = [${triggerGUID}], interactorGUID = [${interactorGUID}]`);

                this.vehicle = await GameObject.asyncFindGameObjectById(vehicleGUID) as AdvancedVehicle;
                this.trigger = await GameObject.asyncFindGameObjectById(triggerGUID) as Trigger;
                this.interactor = await GameObject.asyncFindGameObjectById(interactorGUID) as Interactor;

                this.bindInOutVehicleEvents();
            })
        }
    }

    // Bind trigger events to achieve boarding and alighting functions.
    private bindInOutVehicleEvents(): void {
        // Automatically board the vehicle through a trigger
        this.trigger.onEnter.add(async (chara: Character) => {
            // Determine if it is a trigger triggered by the player character's touch and if it is the current player.
            if (chara && chara.player == await mw.Player.asyncGetLocalPlayer()) {
                // Close character collisions to avoid interaction with vehicles.
                chara.setCollision(CollisionStatus.Off);
                // Activate the interactor and let the character sit on the car.
                this.interactor.enter(chara, mw.HumanoidSlotType.Buttocks, "14015");
                // Set the driver of the vehicle, and then start to simulate physics and drive.
                this.vehicle.owner = chara.player;
                // Adjust some parameters.
                const handle_press_one = InputUtil.onKeyDown(Keys.One, () => {
                    // Press 1 adjust the vehicle mass
                    this.adjustVehicleMass();
                });
                this.controlEventsHandle.push(handle_press_one);

                const handle_press_two = InputUtil.onKeyDown(Keys.Two, () => {
                    // Press 2 adjust the friction coefficient of vehicle
                    this.adjustVehicleFriction();
                });
                this.controlEventsHandle.push(handle_press_two);

                const handle_press_three = InputUtil.onKeyDown(Keys.Three, () => {
                    // Press 3 adjust the maximum engine speed of vehicle
                    this.adjustVehicleMaxEngineRPM();
                });
                this.controlEventsHandle.push(handle_press_three);

                const handle_press_four = InputUtil.onKeyDown(Keys.Four, () => {
                    // Press 4 adjust vehicle acceleration
                    this.adjustVehicleAcceleration();
                });
                this.controlEventsHandle.push(handle_press_four);

                const handle_press_five = InputUtil.onKeyDown(Keys.Five, () => {
                    // Press 5 to adjust the braking torque of the vehicle
                    this.adjustVehicleBrakingTorque();
                });
                this.controlEventsHandle.push(handle_press_five);

                this.VehicleKeyEvents();
            }
        })

        // Monitor the incident of getting off the car.
        mw.Event.addLocalListener(VehicleEvents.outOfVehicle_local, async () => {
            const player = await Player.asyncGetLocalPlayer();
            // Set the exit position to the left of the Trigger.
            const outOfVehicleLoc = this.trigger.worldTransform.position.add(new Vector(0, -100, 50));
            // The interaction ends and the character gets off.
            this.interactor.leave(outOfVehicleLoc);
            // Enable character collision to avoid falling to the ground and other incorrect collisions.
            player.character.setCollision(CollisionStatus.On);
            // Empty the driver of the vehicle. At this time, physics will still be simulated, but control cannot continue.
            this.vehicle.owner = null;

            this.clearControlEvents();
        })
    }

    // Control the movement of the vehicle through buttons.
    private VehicleKeyEvents() {
        this.clearControlEvents();

        //Press the UP button to refuel the vehicle and move forward;
        const handle_up_1 = InputUtil.onKeyDown(Keys.W, () => {
            this.vehicle.throttleInput = 1;
        });
        const handle_up_0 = InputUtil.onKeyUp(Keys.W, () => {
            this.vehicle.throttleInput = 0;
        });
        this.controlEventsHandle.push(handle_up_1, handle_up_0);

        //Press Down to slow down the vehicle;
        const handle_down_1 = InputUtil.onKeyDown(Keys.S, () => {
            this.vehicle.throttleInput = -1;
        });
        const handle_down_0 = InputUtil.onKeyUp(Keys.S, () => {
            this.vehicle.throttleInput = 0;
        });
        this.controlEventsHandle.push(handle_down_1, handle_down_0);

        //Press LEFT to turn the vehicle left;
        const handle_left_1 = InputUtil.onKeyDown(Keys.A, () => {
            this.vehicle.steeringInput = -1;
        });
        const handle_left_0 = InputUtil.onKeyUp(Keys.A, () => {
            this.vehicle.steeringInput = 0;
        });
        this.controlEventsHandle.push(handle_left_1, handle_left_0);

        //Press the RIGHT key to make the vehicle turn right;
        const handle_right_1 = InputUtil.onKeyDown(Keys.D, () => {
            this.vehicle.steeringInput = 1;
        });
        const handle_right_0 = InputUtil.onKeyUp(Keys.D, () => {
            this.vehicle.steeringInput = 0;
        });
        this.controlEventsHandle.push(handle_right_1, handle_right_0);

        //Press the SpaceBar button to brake the vehicle;
        const handle_spaceBar_1 = InputUtil.onKeyDown(Keys.SpaceBar, () => {
            this.vehicle.handbrakeInputEnable = true;
        });
        const handle_spaceBar_0 = InputUtil.onKeyUp(Keys.SpaceBar, () => {
            this.vehicle.handbrakeInputEnable = false;
        });
        this.controlEventsHandle.push(handle_spaceBar_1, handle_spaceBar_0);

        //Press key F to get out.
        const handle_f = InputUtil.onKeyDown(Keys.F, () => {
            mw.Event.dispatchToLocal(VehicleEvents.outOfVehicle_local);
        });
        this.controlEventsHandle.push(handle_f);
    }

    // Unbind button event.
    private clearControlEvents(): void {
        for (const handle of this.controlEventsHandle) {
            handle.isConnected && handle.disconnect();
        }

        this.controlEventsHandle = [];
    }

    // Adjust the mass of vehicle (1500 and 10000 switch back and forth).
    private adjustVehicleMass(): void {
        if (this.vehicle.mass == 1500) {
            this.vehicle.mass = 10000;
        } else {
            this.vehicle.mass = 1500;
        }
    }

    // Adjust the friction coefficient of vehicle (switch back and forth between 0.01 and 3).
    private adjustVehicleFriction(): void {
        if (this.vehicle.friction == 3) {
            this.vehicle.friction = 0.01;
        } else {
            this.vehicle.friction = 3;
        }
    }

    // Adjust the maximum speed of vehicle engine (1000 and 6000 switch back and forth).
    private adjustVehicleMaxEngineRPM(): void {
        if (this.vehicle.maxEngineRPM == 6000) {
            this.vehicle.maxEngineRPM = 1000;
        } else {
            this.vehicle.maxEngineRPM = 6000;
        }
    }

    // Adjust the acceleration of vehicle (switch back and forth between 0.1 and 1).
    private adjustVehicleAcceleration(): void {
        if (this.vehicle.acceleration == 1) {
            this.vehicle.acceleration = 0.1;
        } else {
            this.vehicle.acceleration = 1;
        }
    }

    // Adjust the brake torque of vehicle (switch back and forth between 0 and 1500).
    private adjustVehicleBrakingTorque(): void {
        if (this.vehicle.brakingTorque == 1500) {
            this.vehicle.brakingTorque = 0;
        } else {
            this.vehicle.brakingTorque = 1500;
        }
    }
}

Hierarchy

Table of contents

Properties

vehicleLog: any
click

Properties

onBeforeDestroyDelegate: MulticastDelegate<() => void> other
Event callback before object destruction
onCustomPropertyChange: Readonly<MulticastDelegate<(path: string, value: unknown, oldValue: unknown) => void>> other
Monitor custom attribute synchronization events
onDestroyDelegate: MulticastDelegate<() => void> other
Event callback after object destruction
onPropertyChange: Readonly<MulticastDelegate<(path: string, value: unknown, oldValue: unknown) => void>>
Monitor system replicated events

Accessors

acceleration(): number other
Get acceleration.
brakingTorque(): number other
Obtain the brake torque. Unit: N * m
currentGearLevel(): number other
Get the current gear level.
driveMode(): VehicleDriveMode4WNew other
Get the vehicle drive mode.
friction(): number other
Obtain the friction coefficient of vehicle.
handbrakeInputEnable(useHandbrake: boolean): void other
Whether to apply handbrake, true - apply brake, false - cancel brake.
mass(): number other
Obtain quality.
maxEngineRPM(): number other
Obtain the maximum engine speed. Unit: revolutions per minute (r/min)
maxGearLevel(): number other
Obtain the maximum gear level. If the return value is 4, it indicates the presence of [-1, 0, 1, 2, 3, 4] gears.
owner(): Player other
Obtain the driver of the vehicle.
simulatePhysics(shouldSimulate: boolean): void other
Whether to enable physical simulation calculation for four-wheel vehicles needs to be called on the client side.
steeringInput(newInput: number): void other
Control the left/right steering of vehicle, set the steering amplitude, and the value range is [-1,1]. If it is greater than 0, turn right, and if it is less than 0, turn left.
throttleInput(newInput: number): void other
Control the forward/backward movement of the vehicle, set the throttle size within the range of [-1,1], accelerate when it is greater than 0, and decelerate when it is less than 0.
velocity(): number other
Obtain the current driving speed in meters per second (m/s).
wheelNum(): number other
Obtain the number of wheels.
click

Accessors

actorFlagValue(): number other
Get object tags
actorLevel(): number other
Obtain Actor Level
assetId(): string other
Retrieve the UID of the resource currently being used by the object
gameObjectId(): string other
Get the unique identification of an object (a string that uniquely identifies an object).
isDestroyed(): boolean other
Has the current object been destroyed
isReady(): boolean other
Current object status
localTransform(): Transform other
Local transformation of the current object
name(): string other
Return the current object name
netStatus(): NetStatus other
Get the current object synchronization status
parent(): GameObject other
Retrieve the current parent object
tag(): string other
Get the tag of the current object
worldTransform(): Transform other
Current object world transformation

Methods

gearDown(): void other
Lower the gear and switch immediately.
gearUp(): void other
Upgrade one level and switch immediately.
getGearData(gearLevel: number): VehicleGearDataNew other
Retrieve the specified gear attribute
getWheelMaxSteerAngle(wheelId: number): number other
Obtain the maximum steering angle of the wheels, in degrees (°).
getWheelModel(wheelId: number): string other
Retrieve the tire binding object.
getWheelRadius(wheelId: number): number other
Obtain the wheel radius in centimeters (cm).
onDestroy(): void other
Destruction
setCullDistance(inCullDistance: number): void other
Objects beyond this distance between players will be cropped, and the final cropping distance will depend on the image quality level; When this property is modified to ≤ 0, the cropping distance will be automatically adjusted according to the object size (CullDistanceVolume function will be automatically enabled)
setWheelRadius(wheelId: number, Radius: number): void other
Set the wheel radius in centimeters (cm).
click

Methods

addComponent<T: extends Script<T>>(constructor: (...args: unknown[]) => T: extends Script<T>, bInReplicates?: boolean): T: extends Script<T> other
Add a script component
asyncGetChildByName(name: string): Promise<GameObject> other
Asynchronous search for sub objects based on their names
asyncReady(): Promise<GameObject> other
Return after the object is ready
clone(gameObjectInfo?: GameObjectInfo): GameObject other
Copy Objects
destroy(): void other
delete object
getBoundingBox(nonColliding?: boolean, includeFromChild?: boolean, outer?: Vector): Vector other
Get the size of the object's bounding box
getBounds(onlyCollidingComponents: boolean, originOuter: Vector, boxExtentOuter: Vector, includeFromChild?: boolean): void other
Obtain object boundaries
getChildByGameObjectId(gameObjectId: string): GameObject other
Search for sub objects based on gameObjectid
getChildByName(name: string): GameObject other
Search for sub objects by name
getChildByPath(path: string): GameObject other
Find sub objects according to path
getChildren(): GameObject[] other
Obtain sub objects
getChildrenBoundingBoxCenter(outer?: Vector): Vector other
Get the center point of all child objects' bounding box (not including the parent object, if the parent object is unavailable, return [0,0,0])
getChildrenByName(name: string): GameObject[] other
Search for all sub objects by name
getComponent<T: extends Script<T>>(constructor?: (...args: unknown[]) => T: extends Script<T>): T: extends Script<T> other
Get the component of the specified type
getComponentPropertys<T: extends Script<T>>(constructor: (...args: unknown[]) => T: extends Script<T>): Map<string, IPropertyOptions> other
Get property of script component
getComponents<T: extends Script<T>>(constructor?: (...args: unknown[]) => T: extends Script<T>): T: extends Script<T>[] other
Get all component of the specified type
getCustomProperties(): string[] other
Get all customize property
getCustomProperty<T: extends CustomPropertyType>(propertyName: string): T: extends CustomPropertyType other
Get customize property
getCustomPropertyChangeDelegate(property): Readonly<MulticastDelegate<(path: string, value: unknown, oldValue: unknown) => void>> other
Event proxy triggered when a given object property is modified
getPropertyChangeDelegate(property): Readonly<MulticastDelegate<(path: string, value: unknown, oldValue: unknown) => void>> other
Event proxy triggered when a given object property is modified
getVisibility(): boolean other
Obtain whether the object is displayed
isPrefabActor(): boolean other
Return whether the current object is a prefabricated body
moveBy(velocity: Vector, isLocal?: boolean): void other
Smoothly move an object over time according to a given velocity vector
moveTo(targetPosition: Vector, time: number, isLocal?: boolean, onComplete?: () => void): void other
Smoothly move from the current position to the target position within the specified time
rotateBy(rotation: Quaternion Rotation, multiplier: number, isLocal?: boolean): void other
Rotate the object smoothly over time according to the given rotation amount
rotateTo(targetRotation: Quaternion Rotation, time: number, isLocal?: boolean, onComplete?: () => void): void other
Smoothly changes from the current rotation to the target rotation within the specified time
scaleBy(scale: Vector, isLocal?: boolean): void other
Smoothly scale objects over time using a given scaling vector per second
scaleTo(targetScale: Vector, time: number, isLocal?: boolean, onComplete?: () => void): void other
Smoothly changes from the current scale to the target scale within the specified time
setAbsolute(absolutePosition?: boolean, absoluteRotation?: boolean, absoluteScale?: boolean): void other
Set whether the object localTransform is relative to the parent object or the world
setCustomProperty(propertyName: string, value: undefined CustomPropertyType): void other
Set custom attributes
setVisibility(status: boolean PropertyStatus, propagateToChildren?: boolean): void other
Set whether the object is displayed
stopMove(): void other
Interrupt further movement of moveTo() and moveBy()
stopRotate(): void other
Interrupt further rotation from rotateTo() or rotateBy()
stopScale(): void other
Interrupt further scale from ScaleTo() or ScaleBy()
asyncFindGameObjectById(gameObjectId: string): Promise<GameObject> other
Asynchronous search for GameObject through gameObjectid
asyncGetGameObjectByPath(path: string): Promise<GameObject> other
Asynchronously find objects through path
asyncSpawn<T: extends GameObject<T>>(assetId: string, gameObjectInfo?: GameObjectInfo): Promise<T: extends GameObject<T>> other
Asynchronous construction of an object
bulkPivotTo(gameObjects: GameObject[], transforms: Transform[]): void other
Batch set position
findGameObjectById(gameObjectId: string): GameObject other
Search for objects through gameObjectid
findGameObjectByName(name: string): GameObject other
Search for objects by name
findGameObjectsByName(name: string): GameObject[] other
Search for objects by name
findGameObjectsByTag(tag: string): GameObject[] other
Get objects through customize tag
getGameObjectByPath(path: string): GameObject other
Search for objects through paths
spawn<T: extends GameObject<T>>(assetId: string, gameObjectInfo?: GameObjectInfo): T: extends GameObject<T> other
Construct an object

Properties


vehicleLog

Private vehicleLog: any

------------------------------------------ Internal property/function------------------------------------------

Accessors

acceleration

get acceleration(): number other

set acceleration(acceleration): void other

Get acceleration.

Returns

numberVehicle acceleration coefficient

Set acceleration.

Range

[0.01, 100]

Parameters

acceleration numberNew acceleration coefficient default: 1

brakingTorque

get brakingTorque(): number other

set brakingTorque(Torque): void other

Obtain the brake torque. Unit: N * m

Vehicle braking torque refers to the torque applied to the vehicle braking system for deceleration or stopping vehicle motion. It is the torque generated by the braking system, applied to the wheels through brakes such as brake discs and brake pads, thereby reducing the rotational speed of the wheels.

Returns

numberCurrent braking torque

Set the brake torque. Unit: N * m

Range

[0, 1000000]

Parameters

Torque numberNew braking torque default: 1500

currentGearLevel

get currentGearLevel(): number other

set currentGearLevel(level): void other

Get the current gear level.

Returns

numberCurrent gear level

Set the current gear level.

Range

[-1, Maximum gear set]

Precautions

  1. Pay attention to the range of input parameter values.
  2. Set the gear that does not matchmaking with the current speed, and it will automatically adjust to the matchmaking gear. If the current vehicle speed is adjusted to 1st gear, setting 3rd gear directly will gradually decrease to 1st gear (3-2-1).

Parameters

level numberThe gear to be switched to default: 0

driveMode

get driveMode(): VehicleDriveMode4WNew other

Get the vehicle drive mode.

Returns

VehicleDriveMode4WNewVehicle drive mode

friction

get friction(): number other

set friction(friction): void other

Obtain the friction coefficient of vehicle.

Returns

numberVehicle friction coefficient

Set vehicle wheel friction coefficient

Range

[0.01, 8]

Parameters

friction numberNew friction coefficient default: 3

handbrakeInputEnable

set handbrakeInputEnable(useHandbrake): void other

Whether to apply handbrake, true - apply brake, false - cancel brake.

Precautions

When the input value changes, call once. The input value will be maintained, and no continuous call is required.

Parameters

useHandbrake booleanWhether to apply hand brake, true - apply brake, false - cancel brake. default: false

mass

get mass(): number other

set mass(mass): void other

Obtain quality.

Returns

numberVehicle mass, unit: kilogram (kg)

Set the mass of vehicle in kilogram.

Range

[0.01, 100000]

Precautions

  1. Pay attention to the range of input parameter values. Setting a smaller mass may result in unexpected performance such as vehicle shaking.
  2. Setting the quality during operation will reinitialize the vehicle and clear any running status. If the vehicle is in motion, it will stop in place after setting the mass.

Parameters

mass numberSet value default: 1500

maxEngineRPM

get maxEngineRPM(): number other

set maxEngineRPM(RPM): void other

Obtain the maximum engine speed. Unit: revolutions per minute (r/min)

Returns

numberVehicle engine speed

Set the maximum engine speed. Unit: revolutions per minute (r/min)

Range

[100, 5000000]

Parameters

RPM numberNew vehicle engine speed default: 6000

maxGearLevel

get maxGearLevel(): number other

Obtain the maximum gear level. If the return value is 4, it indicates the presence of [-1, 0, 1, 2, 3, 4] gears.

Precautions

The maximum gear that can be switched to. To obtain the current gear, please use getCurrentGearLevel

Returns

numberMaximum gear level

owner

get owner(): Player other

set owner(inOwner): void other

Obtain the driver of the vehicle.

Returns

Player

Set the vehicle driver. Only the driver can operate the vehicle.

Parameters

inOwnerPlayer

simulatePhysics

set simulatePhysics(shouldSimulate): void other

Whether to enable physical simulation calculation for four-wheel vehicles needs to be called on the client side.

Precautions

The four-wheel vehicle will only undergo physical simulation after the set owner is successful. At this time, closing the physical simulation will no longer drive the vehicle to move.

Parameters

shouldSimulate booleanWhether to enable physical simulation. True enable, false disable default: true

steeringInput

set steeringInput(newInput): void other

Control the left/right steering of vehicle, set the steering amplitude, and the value range is [-1,1]. If it is greater than 0, turn right, and if it is less than 0, turn left.

Range

[-1, 1] Turn right when it is greater than 0, and turn left when it is less than 0.

Precautions

  1. Pay attention to the range of input parameter values. There is no difference between entering 100 and 1.
  2. When the input value changes, call once. The input value will be maintained, and no continuous call is required.

Usage example: Control the vehicle with buttons and joysticks

ts
// Control the vehicle throttle through buttons
   this.btn_forward.onPressed.add(() => {
       vehicle.setThrottleInput(1);
   })

   this.btn_forward.onReleased.add(() => {
       vehicle.setThrottleInput(0);
   })

   // By controlling the vehicle with a joystick, the joystick will provide two axial inputs (x, y) simultaneously
   this.joystick.onInputDir.add((vec: mw.Vector2) => {
       // Control throttle
       vehicle.setThrottleInput(vec.y);
       // Control steering
       vehicle.setSteeringInput(vec.x);
   })
// Control the vehicle throttle through buttons
   this.btn_forward.onPressed.add(() => {
       vehicle.setThrottleInput(1);
   })

   this.btn_forward.onReleased.add(() => {
       vehicle.setThrottleInput(0);
   })

   // By controlling the vehicle with a joystick, the joystick will provide two axial inputs (x, y) simultaneously
   this.joystick.onInputDir.add((vec: mw.Vector2) => {
       // Control throttle
       vehicle.setThrottleInput(vec.y);
       // Control steering
       vehicle.setSteeringInput(vec.x);
   })

Parameters

newInput numberSet value default: 0

throttleInput

set throttleInput(newInput): void other

Control the forward/backward movement of the vehicle, set the throttle size within the range of [-1,1], accelerate when it is greater than 0, and decelerate when it is less than 0.

Range

[-1, 1] Accelerate when greater than 0, decelerate when less than 0.

Precautions

  1. Pay attention to the range of input parameter values. There is no difference between entering 100 and 1.
  2. When the input value changes, call once. The input value will be maintained, and no continuous call is required.

Usage example: Control the vehicle with buttons and joysticks

ts
// Control the vehicle throttle through buttons
   this.btn_forward.onPressed.add(() => {
       vehicle.throttleInput = 1;
   })

   this.btn_forward.onReleased.add(() => {
       vehicle.throttleInput = 0;
   })

   // By controlling the vehicle with a joystick, the joystick will provide two axial inputs (x, y) simultaneously
   this.joystick.onInputDir.add((vec: mw.Vector2) => {
       // Control throttle
       vehicle.throttleInput = vec.y;
       // Control steering
       vehicle.steeringInput = vec.x;
   })
// Control the vehicle throttle through buttons
   this.btn_forward.onPressed.add(() => {
       vehicle.throttleInput = 1;
   })

   this.btn_forward.onReleased.add(() => {
       vehicle.throttleInput = 0;
   })

   // By controlling the vehicle with a joystick, the joystick will provide two axial inputs (x, y) simultaneously
   this.joystick.onInputDir.add((vec: mw.Vector2) => {
       // Control throttle
       vehicle.throttleInput = vec.y;
       // Control steering
       vehicle.steeringInput = vec.x;
   })

Parameters

newInput numberSet value default: 0

velocity

get velocity(): number other

Obtain the current driving speed in meters per second (m/s).

Returns

numberCurrent driving speed

wheelNum

get wheelNum(): number other

Obtain the number of wheels.

Returns

numberNumber of wheels

Methods


gearDown

gearDown(): void other

Lower the gear and switch immediately.


gearUp

gearUp(): void other

Upgrade one level and switch immediately.


getGearData

getGearData(gearLevel): VehicleGearDataNew other

Retrieve the specified gear attribute

Parameters

gearLevel numberSpecify gear level range: [0,1] type: floating point number

Returns

VehicleGearDataNewSpecify the gear attribute

Precautions

Pay attention to the range of input parameter values


getWheelMaxSteerAngle

getWheelMaxSteerAngle(wheelId): number other

Obtain the maximum steering angle of the wheels, in degrees (°).

Parameters

wheelId numberSpecify the wheel according to the serial number
range: 0.1.2.3 four parameters type: integer

Returns

numberSpecify the maximum steering angle of the specified wheel

Pay attention to the range of input parameter values. The current vehicle is a four-wheel vehicle, with [0, 1, 2, 3] corresponding to [left front, right front, left rear, right rear].


getWheelModel

getWheelModel(wheelId): string other

Retrieve the tire binding object.

Parameters

wheelId numberSpecify the wheel according to the serial number
range: 0.1.2.3 four parameters type: integer

Returns

stringSpecify the tire binding object UID

Pay attention to the range of input parameter values. The current vehicle is a four-wheel vehicle, with [0, 1, 2, 3] corresponding to [left front, right front, left rear, right rear].


getWheelRadius

getWheelRadius(wheelId): number other

Obtain the wheel radius in centimeters (cm).

Parameters

wheelId numberSpecify the wheel according to the serial number
range: 0.1.2.3 four parameters type: integer

Returns

numberSpecify wheel radius

Pay attention to the range of input parameter values. The current vehicle is a four-wheel vehicle, with [0, 1, 2, 3] corresponding to [left front, right front, left rear, right rear].


onDestroy

Protected onDestroy(): void other

Destruction


setCullDistance

setCullDistance(inCullDistance): void other

Objects beyond this distance between players will be cropped, and the final cropping distance will depend on the image quality level; When this property is modified to ≤ 0, the cropping distance will be automatically adjusted according to the object size (CullDistanceVolume function will be automatically enabled)

Parameters

inCullDistance numberUsage: cull distance range: recommended (2000, 4000) type: floating point

Precautions

The final cull distance will be related to the graphics quality level


setWheelRadius

setWheelRadius(wheelId, Radius): void other

Set the wheel radius in centimeters (cm).

Parameters

wheelId numberSpecify the wheel according to the serial number
range: 0.1.2.3 four parameters type: integer
Radius numberSpecify wheel radius range: No restrictions, reasonable is sufficient Type: Floating point number

Pay attention to the range of input parameter values. The current vehicle is a four-wheel vehicle, with [0, 1, 2, 3] corresponding to [left front, right front, left rear, right rear]. It only takes effect before boarding, and call this API after boarding has no effect.