- Home /
Continuous moving ball stuck at some time
I am working on 2d game where monster with circular body moving continuously on screen. I have established grid which get filled by player movement so overall area for monster gets reduced based on player cover its area.
Using following code monster is moving continuously but at some point it get stuck at some corner and stop moving.
public class EnemyMovement : MonoBehaviour
{
private bool isStartMoving;
private Vector3 direction;
private float sFactor = 10.0f;
private float localScaleX, localScaleY;
//
public float cSpeed = 5.0f;
void Start ()
{
InitializeValues ();
}
private void InitializeValues ()
{
localScaleX = transform.localScale.x;
localScaleY = transform.localScale.y;
float xDirection = Random.Range (0, 2) * 2 - 1;
float yDirection = Random.Range (0, 2) * 2 - 1;
direction = new Vector3 (xDirection * cSpeed, yDirection * cSpeed, 0f);
rigidbody2D.velocity = direction;
isStartMoving = true;
}
void FixedUpdate ()
{
if (!isStartMoving)
return;
// current velocity
Vector3 cVel = rigidbody2D.velocity;
if (cVel == Vector3.zero)
return;
// normalized vector * constant speed
Vector3 tVel = cVel.normalized * cSpeed;
if (tVel.x > 0)
tVel.x = cSpeed;
else
tVel.x = -cSpeed;
if (tVel.y > 0)
tVel.y = cSpeed;
else
tVel.y = -cSpeed;
rigidbody2D.velocity = Vector3.Lerp (cVel, tVel, Time.deltaTime * sFactor);
}
}
I have assign physics material in following manner.
Please give some guidance in this.
Something like this type of situation happening with me.
You clearly see in image bottom right corner monster is sleeping though continuous movement code is running. Please give me suggestion to improve this.
$$anonymous$$y guess is
if (cVel == Vector3.zero)
return;
is the problem. If the monster ever stops moving, it will never start again unless some outside force hits it.
Okay, thanks let me try with your suggestion. I reply back to here after some time because this type of condition happen sometime only.