javascript - Raycast in Unity2D can't seem to find the floor -
i'm trying use raycast let game know when character in air, or more importantly when on ground. simple raycast should trick no matter try keeps returning false. both player , floor have colliders attached, here relevant code.
pragma strict
var leftkey: keycode; var rightkey: keycode; var jumpkey: keycode; var playerspeed = 7; var onfloor = false; var disttoground: float; function start () { // distance ground disttoground = getcomponent.<collider2d>().bounds.extents.y + 0.1f; } function isgrounded(): boolean { return physics.raycast(getcomponent.<collider2d>().bounds.center, vector3.down, disttoground, 1 << 8); } function update () { debug.log("" + isgrounded()); if (isgrounded()){ if(input.getkey(leftkey)){ getcomponent.<rigidbody2d>().velocity.x = playerspeed * -1; } else if(input.getkey(rightkey)){ getcomponent.<rigidbody2d>().velocity.x = playerspeed; } if(input.getkeydown(jumpkey)){ getcomponent.<rigidbody2d>().addforce(new vector2(0,380)); } } else if (!isgrounded()) { if(input.getkey(leftkey)){ getcomponent.<rigidbody2d>().addforce(new vector2(-2,0)); } else if(input.getkey(rightkey)){ getcomponent.<rigidbody2d>().addforce(new vector2(2,0)); } } } i've been stuck on while , i'm pretty sure i'm idiot missing simple or i've been reading out of date materials.
two things:
your
isgrounded()function has typo. shouldgetcomponent<collider2d>(), notgetcomponent.<collider2d>()try increasing value of
disttogroundfloat, in case raycast going in right direction, not far enough.
i hope helps!
Comments
Post a Comment