How do i add sliding to my game

Game: PlayCanvas | HTML5 Game Engine
Editor: PlayCanvas | HTML5 Game Engine

// Some stupid rigidbody based movement by Dani

public class PlayerMovement : MonoBehaviour {

    //Assingables
    public Transform playerCam;
    public Transform orientation;
    
    //Other
    private Rigidbody rb;

    //Rotation and look
    private float xRotation;
    private float sensitivity = 50f;
    private float sensMultiplier = 1f;
    
    //Movement
    public float moveSpeed = 4500;
    public float maxSpeed = 20;
    public bool grounded;
    public LayerMask whatIsGround;
    
    public float counterMovement = 0.175f;
    private float threshold = 0.01f;
    public float maxSlopeAngle = 35f;

    //Crouch & Slide
    private Vector3 crouchScale; = new Vector3(1, 0.5f, 1);
    private Vector3 playerScale;
    public float slideForce = 400;
    public float slideCounterMovement = 0.2f;

    //Jumping
    private bool readyToJump = true;
    private float jumpCooldown = 0.25f;
    public float jumpForce = 550f;
    
    //Input
    float x, y;
    bool jumping, sprinting, crouching;
    
    //Sliding
    private Vector3 normalVector = Vector3.up;
    private Vector3 wallNormalVector;

    void Awake() {
        rb = GetComponent<Rigidbody>();
    }
    
    void Start() {
        playerScale =  transform.localScale;
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    
    private void FixedUpdate() {
        Movement();
    }

    private void Update() {
        MyInput();
        Look();
    }

    /// <summary>
    /// Find user input. Should put this in its own class but im lazy
    /// </summary>
    private void MyInput() {
        x = Input.GetAxisRaw("Horizontal");
        y = Input.GetAxisRaw("Vertical");
        jumping = Input.GetButton("Jump");
        crouching = Input.GetKey(KeyCode.LeftControl);
      
        //Crouching
        if (Input.GetKeyDown(KeyCode.LeftControl))
            StartCrouch();
        if (Input.GetKeyUp(KeyCode.LeftControl))
            StopCrouch();
    }

    private void StartCrouch() {
        transform.localScale = crouchScale;
        transform.position = new Vector3(transform.position.x, transform.position.y - 0.5f, transform.position.z);
        if (rb.velocity.magnitude > 0.5f) {
            if (grounded) {
                rb.AddForce(orientation.transform.forward * slideForce);
            }
        }
    }

    private void StopCrouch() {
        transform.localScale = playerScale;
        transform.position = new Vector3(transform.position.x, transform.position.y + 0.5f, transform.position.z);
    }

    private void Movement() {
        //Extra gravity
        rb.AddForce(Vector3.down * Time.deltaTime * 10);
        
        //Find actual velocity relative to where player is looking
        Vector2 mag = FindVelRelativeToLook();
        float xMag = mag.x, yMag = mag.y;

        //Counteract sliding and sloppy movement
        CounterMovement(x, y, mag);
        
        //If holding jump && ready to jump, then jump
        if (readyToJump && jumping) Jump();

        //Set max speed
        float maxSpeed = this.maxSpeed;
        
        //If sliding down a ramp, add force down so player stays grounded and also builds speed
        if (crouching && grounded && readyToJump) {
            rb.AddForce(Vector3.down * Time.deltaTime * 3000);
            return;
        }
        
        //If speed is larger than maxspeed, cancel out the input so you don't go over max speed
        if (x > 0 && xMag > maxSpeed) x = 0;
        if (x < 0 && xMag < -maxSpeed) x = 0;
        if (y > 0 && yMag > maxSpeed) y = 0;
        if (y < 0 && yMag < -maxSpeed) y = 0;

        //Some multipliers
        float multiplier = 1f, multiplierV = 1f;
        
        // Movement in air
        if (!grounded) {
            multiplier = 0.5f;
            multiplierV = 0.5f;
        }
        
        // Movement while sliding
        if (grounded && crouching) multiplierV = 0f;

        //Apply forces to move player
        rb.AddForce(orientation.transform.forward * y * moveSpeed * Time.deltaTime * multiplier * multiplierV);
        rb.AddForce(orientation.transform.right * x * moveSpeed * Time.deltaTime * multiplier);
    }

    private void Jump() {
        if (grounded && readyToJump) {
            readyToJump = false;

            //Add jump forces
            rb.AddForce(Vector2.up * jumpForce * 1.5f);
            rb.AddForce(normalVector * jumpForce * 0.5f);
            
            //If jumping while falling, reset y velocity.
            Vector3 vel = rb.velocity;
            if (rb.velocity.y < 0.5f)
                rb.velocity = new Vector3(vel.x, 0, vel.z);
            else if (rb.velocity.y > 0) 
                rb.velocity = new Vector3(vel.x, vel.y / 2, vel.z);
            
            Invoke(nameof(ResetJump), jumpCooldown);
        }
    }
    
    private void ResetJump() {
        readyToJump = true;
    }
    
    private float desiredX;
    private void Look() {
        float mouseX = Input.GetAxis("Mouse X") * sensitivity * Time.fixedDeltaTime * sensMultiplier;
        float mouseY = Input.GetAxis("Mouse Y") * sensitivity * Time.fixedDeltaTime * sensMultiplier;

        //Find current look rotation
        Vector3 rot = playerCam.transform.localRotation.eulerAngles;
        desiredX = rot.y + mouseX;
        
        //Rotate, and also make sure we dont over- or under-rotate.
        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

        //Perform the rotations
        playerCam.transform.localRotation = Quaternion.Euler(xRotation, desiredX, 0);
        orientation.transform.localRotation = Quaternion.Euler(0, desiredX, 0);
    }

    private void CounterMovement(float x, float y, Vector2 mag) {
        if (!grounded || jumping) return;

        //Slow down sliding
        if (crouching) {
            rb.AddForce(moveSpeed * Time.deltaTime * -rb.velocity.normalized * slideCounterMovement);
            return;
        }

        //Counter movement
        if (Math.Abs(mag.x) > threshold && Math.Abs(x) < 0.05f || (mag.x < -threshold && x > 0) || (mag.x > threshold && x < 0)) {
            rb.AddForce(moveSpeed * orientation.transform.right * Time.deltaTime * -mag.x * counterMovement);
        }
        if (Math.Abs(mag.y) > threshold && Math.Abs(y) < 0.05f || (mag.y < -threshold && y > 0) || (mag.y > threshold && y < 0)) {
            rb.AddForce(moveSpeed * orientation.transform.forward * Time.deltaTime * -mag.y * counterMovement);
        }
        
        //Limit diagonal running. This will also cause a full stop if sliding fast and un-crouching, so not optimal.
        if (Mathf.Sqrt((Mathf.Pow(rb.velocity.x, 2) + Mathf.Pow(rb.velocity.z, 2))) > maxSpeed) {
            float fallspeed = rb.velocity.y;
            Vector3 n = rb.velocity.normalized * maxSpeed;
            rb.velocity = new Vector3(n.x, fallspeed, n.z);
        }
    }

    /// <summary>
    /// Find the velocity relative to where the player is looking
    /// Useful for vectors calculations regarding movement and limiting movement
    /// </summary>
    /// <returns></returns>
    public Vector2 FindVelRelativeToLook() {
        float lookAngle = orientation.transform.eulerAngles.y;
        float moveAngle = Mathf.Atan2(rb.velocity.x, rb.velocity.z) * Mathf.Rad2Deg;

        float u = Mathf.DeltaAngle(lookAngle, moveAngle);
        float v = 90 - u;

        float magnitue = rb.velocity.magnitude;
        float yMag = magnitue * Mathf.Cos(u * Mathf.Deg2Rad);
        float xMag = magnitue * Mathf.Cos(v * Mathf.Deg2Rad);
        
        return new Vector2(xMag, yMag);
    }

    private bool IsFloor(Vector3 v) {
        float angle = Vector3.Angle(Vector3.up, v);
        return angle < maxSlopeAngle;
    }

    private bool cancellingGrounded;
    
    /// <summary>
    /// Handle ground detection
    /// </summary>
    private void OnCollisionStay(Collision other) {
        //Make sure we are only checking for walkable layers
        int layer = other.gameObject.layer;
        if (whatIsGround != (whatIsGround | (1 << layer))) return;

        //Iterate through every collision in a physics update
        for (int i = 0; i < other.contactCount; i++) {
            Vector3 normal = other.contacts[i].normal;
            //FLOOR
            if (IsFloor(normal)) {
                grounded = true;
                cancellingGrounded = false;
                normalVector = normal;
                CancelInvoke(nameof(StopGrounded));
            }
        }

        //Invoke ground/wall cancel, since we can't check normals with CollisionExit
        float delay = 3f;
        if (!cancellingGrounded) {
            cancellingGrounded = true;
            Invoke(nameof(StopGrounded), Time.deltaTime * delay);
        }
    }

    private void StopGrounded() {
        grounded = false;
    }
    
}

@Riply_Sus Could you provide some more information on what you are looking for in the way of help. I assume that the above script you are showing is from Unity? I see you included it as a Javascript code element in your project. Are you looking to convert this code?

yes im trying to add in a sliding mechanic made by dani which is not working so im trying to figure out how to change the script to make it run like the one in the video but this is not the same software so im trying to add it my game but its not working cause its unity How to Make Grappling Gun in Unity (Tutorial) - YouTube

here is the one im trying to make

@Riply_Sus First I think maybe there are two different types you want to convert to Playcanvas. Looks like the Grapple with gun and the sliding effect on FPS movement. The sliding effect video does not offer a lot of information other than just some player/scene setup and then he just copies a predesigned Unity C# module into the game. Toward the end of this video there is a bit more detail(Not a lot) that could be helpful. In comparison to your Movement script you should be able to see a lot of similarities. Please have a look to the rigidbody settings for your player.

image

By adjusting the Mass, Linear Damping, and Friction you could create the effect you are looking for. Actually I think I remember seeing this in the video.

Here is the API Reference.
https://developer.playcanvas.com/api/pc.RigidBodyComponent.html

You can adjust movement either by code like the video or you could simply use the player rigidbody settings to experiment.

2 Likes

there is another video if you click his Chanel and got to the playlist given and it talks about his movement but im new js and i don’t really get it

is this how i do it

// Create a static 1x1x1 box-shaped rigid body

const entity = pc.Entity();

entity.addComponent("rigidbody", {

type: pc.BODYTYPE_DYNAMIC,

mass: 10

});

entity.addComponent("collision", {

type: "sphere"

});

const entity = pc.Entity();

entity.addComponent("rigidbody", {

type: pc.BODYTYPE_DYNAMIC,

mass: 10

});

entity.addComponent("collision", {

type: "sphere"

});

// Apply an approximation of gravity at the body's center

this.entity.rigidbody.applyForce(0, -10, 0);

// Apply an approximation of gravity at 1 unit down the world Z from the center of the body

this.entity.rigidbody.applyForce(0, -10, 0, 0, 0, 1);

// Apply a force at the body's center

// Calculate a force vector pointing in the world space direction of the entity

var force = this.entity.forward.clone().mulScalar(100);

// Apply the force

this.entity.rigidbody.applyForce(force);

// Apply a force at some relative offset from the body's center

// Calculate a force vector pointing in the world space direction of the entity

var force = this.entity.forward.clone().mulScalar(100);

// Calculate the world space relative offset

var relativePos = new pc.Vec3();

var childEntity = this.entity.findByName('Engine');

relativePos.sub2(childEntity.getPosition(), this.entity.getPosition());

// Apply the force

this.entity.rigidbody.applyForce(force, relativePos);

// Apply an impulse along the world-space positive y-axis at the entity's position.

var impulse = new pc.Vec3(0, 10, 0);

entity.rigidbody.applyImpulse(impulse);

// Apply an impulse along the world-space positive y-axis at 1 unit down the positive

// z-axis of the entity's local-space.

var impulse = new pc.Vec3(0, 10, 0);

var relativePoint = new pc.Vec3(0, 0, 1);

entity.rigidbody.applyImpulse(impulse, relativePoint);

// Apply an impulse along the world-space positive y-axis at the entity's position.

entity.rigidbody.applyImpulse(0, 10, 0);

// Apply an impulse along the world-space positive y-axis at 1 unit down the positive

// z-axis of the entity's local-space.

entity.rigidbody.applyImpulse(0, 10, 0, 0, 0, 1);

// Apply via vector

var torque = new pc.Vec3(0, 10, 0);

entity.rigidbody.applyTorque(torque);

// Apply via numbers

entity.rigidbody.applyTorque(0, 10, 0);

// Teleport the entity to the origin

entity.rigidbody.teleport(pc.Vec3.ZERO);

// Teleport the entity to the origin

entity.rigidbody.teleport(0, 0, 0);

// Teleport the entity to world-space coordinate [1, 2, 3] and reset orientation

var position = new pc.Vec3(1, 2, 3);

entity.rigidbody.teleport(position, pc.Vec3.ZERO);

// Teleport the entity to world-space coordinate [1, 2, 3] and reset orientation

entity.rigidbody.teleport(1, 2, 3, 0, 0, 0);

obj.on('test', function () { }); // bind an event to 'test'

obj.hasEvent('test'); // returns true

obj.hasEvent('hello'); // returns false

var handler = function () {

};

obj.on('test', handler);

obj.off(); // Removes all events

obj.off('test'); // Removes all events called 'test'

obj.off('test', handler); // Removes all handler functions, called 'test'

obj.off('test', handler, this); // Removes all handler functions, called 'test' with scope thi

obj.on('test', function (a, b) {

console.log(a + b);

});

obj.fire('test', 1, 2); // prints 3 to the console

obj.once('test', function (a, b) {

console.log(a + b);

});

obj.fire('test', 1, 2); // prints 3 to the console

obj.fire('test', 1, 2); // not going to get handled

@Riply_Sus It looks like this script is using the Playcanvas engine however the code is at a much deeper level than what you will need to deal with. You will not have to handle the creation of objects in such a raw fashion when using the editor. You can create the object such as a player which is a capsule entity and your can add components to it like collision and rigid body. However, in this code is some of the physics you could use to do what you are looking for but will not be a drop in replacement. Can I ask where you found this code? Or did you write it?

This section of the user manual should show a pretty good explanation of scripts in Playcanvas.
https://developer.playcanvas.com/en/user-manual/scripting/

Have you been able to try what I suggested?

i found it in multiple games and added multiplayer network software

how do i let you edit my code or your not allowed to ok im do it hold up