Is this script correct? (Moving player at straight direction untill they Crash)

Can this script move player at straight direction untill they Crash?

var PlayerMovement = pc.createScript('playerMovement');

PlayerMovement.attributes.add('speed', {type: 'number', default: 1});

// initialize code called once per entity
PlayerMovement.prototype.initialize = function() {
    // Set initial movement direction
    this.direction = new pc.Vec3(0, 0, -1);
};

// update code called every frame
PlayerMovement.prototype.update = function(dt) {
    // Check for collision with any objects in front of player
    var result = this.entity.raycast(this.entity.getPosition(), this.direction, 1);
    if (result) {
        // Stop moving forward if collision detected
        this.speed = 0;
    }
    
    // Move player left or right based on input
    if (this.app.keyboard.isPressed(pc.KEY_LEFT)) {
        this.entity.translate(-this.speed * dt, 0, 0);
    } else if (this.app.keyboard.isPressed(pc.KEY_RIGHT)) {
        this.entity.translate(this.speed * dt, 0, 0);
    }
    
    // Move player forward
    this.entity.translate(0, 0, -this.speed * dt);
};

Hi @MATURE,

Have you tested it?

It seems it could work if you set everything up correctly. That would involve selecting the right axis for movement, adding the right components (collision and rigidbody) to both the player and obstacles and setting their properties right (e.g. set the player to be a kinematic rigid body).

not yet tested it is written by chatgpt

when i run it it says:
this.entity.raycast is not a function
in this code:

var result = this.entity.raycast(this.entity.getPosition(), this.direction, 1);

The correct definition is:

var result = this.entity.rigidbody.raycastFirst(startPos, endPos);

You should start with PlayCanvas user manual and tutorials to better understand this code:

https://developer.playcanvas.com

And here is the API for the raycastFirst method: RigidBodyComponentSystem | PlayCanvas API Reference

1 Like

@MATURE Please keep all your posts about the same topic in the same thread. This isn’t a chat room where you need to make a new topic per post :slight_smile:

1 Like

@yaustar Sorry about that :sweat_smile: :face_with_peeking_eye: :sweat:
then pls can you tell how to make player go forward without keyboard or mouse input