I know this question sounds familiar but I'm working on a pretty big platformer (Written in PJS, on Khan Academy) and I don't want it to be just plain ground, I want slopes in the game (gentle slopes, steep, curvy, and smoothened) But I don't really know how to code it and the correct collision since I want it to feel like slopes in a sonic game where you can freely move but just going fast can make speeding through the level.
Here's a link to my project.
var slopeCollision = function(??){ return; }; var gravity = 2; // acceleration due to gravity in pixel/frame² var Slope = function(x, y, w, h) { this.x = x; this.y = y; this.w = w; // run this.h = h; // rise var mag = Math.hypot(w, h); var ux = w / mag; // unit run, aka cosine var uy = h / mag; // unit rise, aka sine var acc = uy * gravity; // scaler acceleration due to gravity this.ddx = ux * acc; // X axis acceleration due to gravity this.ddy = uy * acc; // Y axis acceleration due to gravity }; Slope.prototype.draw = function(cam) { var view = cam.view(this); if(view){ ellipse(view.x, view.y, 5, 5); line(view.x, view.y, view.x + view.w, view.y + view.h); ellipse(view.x + view.w, view.y + view.h, 2, 2); } }; /* * Apply this Slope's acceleration to obj. * Acceleration affects obj's velocity. * Obj's velocity affects its position. */ Slope.prototype.applyAcceleration = function(obj) { obj.dx += this.ddx; obj.x += obj.dx; obj.dy += this.ddy; obj.y += obj.dy; var gradient = 0.5; var yOffset = 0; for(var i = 0; i < circles.length; i++){ if(Collision(this, circles[i])){ circles[i].y = gradient * slope[0].x + yOffset; } } }; slope.add = function(x,y,w,h){ this.push(new Slope(x, y, w, h)); }; slope.apply = function(cam, circles){ for(var i = 0; i < this.length; i++){ this[i].draw(cam); this[i].applyAcceleration(circles); } }; Here's the images of the aforementioned slopes:
- Curvy: https://i.sstatic.net/DupVaT4E.png
- Smooth: https://i.sstatic.net/EK1DlgZP.png
- Steep: https://i.sstatic.net/z1SJ22Y5.png
- Gentle: https://i.sstatic.net/828MlD0T.png
- Downward: https://i.sstatic.net/w9tN7FY8.png