How to fix/get rid of "magnetism" with velocity+gravity+jump+collision in p5.js Play?

I'm trying to figure out how to make "human" to move, jump and "bump" like in Super Mario. So far I made basic velocity movement on X axis, collision with canvas edges, velocity += gravity (works fine), made jump. I added small random platforms to test jump, jumping on top of them is fine, the problem is human gets stuck on the side of platform.

I think there is a way to detect which side of platform human is colliding with, but I just can't figure it out yet :) pls help :)

P.S. I can give some code if needed :)

Answers

  • edited October 2017

    To even start helping you, I would need to write code to move a thing about, that has velocity and gravity and boundaries and then - maybe - I can see what your problem is based on your brief description. That is a ton of work for probably no payoff. And you already have it done, and could post your code that shows the problem.

    Yeah, I think YOU SHOULD POST YOUR CODE.

  • edited October 2017
    var human;
    var scrCol;
    var platforms;
    var GRAVITY = 0.2;
    var JUMP = 15;
    var jumping = false;
    
    function setup() {
        createCanvas(600, 600);
    
        human = createSprite(width/2, height/2);
        human.addAnimation("normal", "pics/real_boy.png");
    
        plats = new Group();
    
        for (var i=0; i<20; i++) {
            var plat = createSprite(random(30, width-30), random(10, height-10), 60, 20);
            plats.add(plat);
        }
    }
    
    function draw() {
        background(191);
    
        //Movement x axis
        if (keyDown("a")) {
            human.velocity.x -= 1;
        } else if (keyDown("d")) {
            human.velocity.x += 1;
        }
        human.velocity.x = human.velocity.x/1.2;
    
        //Movement y axix + gravity
        human.velocity.y += GRAVITY;
    
        if (keyDown("space") && !jumping) {
            human.velocity.y = -JUMP;
            jumping = true;
        }
    
        if (human.collide(plats)) {
            human.velocity.y = 0;
            if (jumping) jumping = false;
        }
    
        scrCol(); //Canvas collision
    
        human.maxSpeed = 7; //Speeks for it sefl...
    
        drawSprites();
    }
    
  • I haven't run your code. One common cheat in this situation is to make the character 'bounce' when a collision is detected. I've not used the library, but you could try this:

     if (human.collide(plats)) {
      human.velocity.y *= -1;
      human.velocity.x *= -1;
      if (jumping) {
        jumping = false;
      }
    }
    

    In this case you don't need to know the side that was hit: you simply reverse the direction of travel... The only problem you may have is that the play library may internally have already set velocity to 0 on collision :/

Sign In or Register to comment.