Before I begin, I would like to note that I’m not quite sure which forum to post this in, so I chose the most related one. ![]()
I have written a javascript “Smart Jump” that will jump a player to the block above it [with multi-jump capability]. I also included the character controller script along with it. Here it is!:
//This game is block/tile-based, so each 40x40 sprite is changed with [Pixels to Units] so they are 1x1 unit.
#pragma strict
var speed = 0.05;
var maxJump = 3;
private var jump = 1;
function Start()
{
//Freeze rotation +fix z-rotation problem [player spawns and immediately collides, causing slight z rotation, but with my initiation script (spawn blocks according to position in array)]
transform.eulerAngles.z = 0;
rigidbody2D.fixedAngle = true;
}
function Update()
{
//Check for collision in all directions [fortunately not *that* FPS intensive]
var right : RaycastHit2D = Physics2D.Raycast(Vector2(transform.position.x+0.5,transform.position.y), Vector2.right, 0.00001);
var left : RaycastHit2D = Physics2D.Raycast(Vector2(transform.position.x-0.5,transform.position.y), -Vector2.right, 0.00001);
var down : RaycastHit2D = Physics2D.Raycast(Vector2(transform.position.x,transform.position.y-0.501), -Vector2.up, 0.1);
//Get right-left input
if(Input.GetKey("d") !right)
transform.Translate(Vector3( speed,0,0));
else if(Input.GetKey("a") !left)
transform.Translate(Vector3(-speed,0,0));
//Get jump input + check if exceeded maxJump
if(Input.GetKeyDown("w") jump < maxJump)
{
jump++;
//Get the distance towards to nearest block
var distance = (Mathf.Round(transform.position.y+1) - transform.position.y)+0.05;
//Reset y velocity
rigidbody2D.velocity.y = 0.0;
//Forumla for distance jumps
rigidbody2D.velocity.y += Mathf.Sqrt(distance * 2 * -Physics.gravity.y);
}
//Reset jump count if grounded
if(down)
jump = 1;
}
Thanks!
|Edits->
|| 1: Slightly changed jump height +[0.01]
|| 2:Added raycast for checking if player grounded +changed raycast length
|| 3:Slightly changed maxjump code [starts at one now]