Something is odd with my javascript for a simple enemy patrol for my 2d platformer game. It detects the edge of the collider it is walking on and flips the sprite. My script isn't triggering errors, but the enemy will simply stay in place and continuously flip left and right rapidly. Please help!!!
#pragma strict
public var speed : float;
public var enemyMask : LayerMask;
private var myBody : Rigidbody2D;
private var myTrans : Transform;
private var myWidth : float;
function Start () {
myTrans = this.transform;
myBody = this.GetComponent(Rigidbody2D);
myWidth = this.GetComponent(SpriteRenderer).bounds.extents.x;
}
function FixedUpdate () {
var lineCastPos : Vector2 = myTrans.position - myTrans.right * myWidth;
var isGrounded : boolean = Physics2D.Linecast (lineCastPos, lineCastPos + Vector2.down, enemyMask);
if (!isGrounded) {
var currRot : Vector3 = myTrans.eulerAngles;
currRot.y += 180;
myTrans.eulerAngles = currRot;
}
var myVel : Vector2 = myBody.velocity;
myVel.x = -myTrans.right.x * speed;
myBody.velocity = myVel;
}
↧