gravity on enemies

Hey all,

I have another question on scripting. I am making an enemy crab character that is supposed to chase my player. I am using a simple collider and rigidbody setup but the way I have it scripted, the crab won’t actually react to gravity. If my player jumps the crab follows him into the air. Here is the code:

var speed : float; 
var player : Transform;
var gravity = 3.0;


private var moveDirection = Vector3.zero;

function Update() {
	
		var distFromPlayer : Vector3 = player.position - transform.position;
		var target : Vector3;
		var velocity = rigidbody.velocity;
		
			// Apply gravity
	moveDirection.y -= gravity * Time.deltaTime;
				
		if(distFromPlayer.magnitude < 20){
			target = player.position;
			velocity = (player.position - transform.position).normalized * speed;
			}
	
	rigidbody.velocity = velocity; 
	transform.LookAt(target);

	
}

var CrabDamage = 5.0;
var hitEffect : GameObject;
private var hit : Collision;
 

function OnCollisionEnter(hit : Collision) {

		
		//Send a damage message to the hit object
		if (hit.collider.tag == "Player" || hit.collider.tag == "Enemy")
		{
			/*Instantiate(hitEffect, hit.point, Quaternion.identity);*/
			hit.collider.SendMessage("ApplyDamage", CrabDamage, SendMessageOptions.DontRequireReceiver);
			
			
			if (hit.collider.tag == "Player"){
			// Destroy the projectile
			Destroy(gameObject);
			}
			
}
}

Does anyone have any ideas?

You have a fair bit of redundant stuff in your script. You have a variable called “moveDirection” that you don’t seem to use.

Try this :

function Update() { 
    
      var distFromPlayer : Vector3 = player.position - transform.position; 
      var target : Vector3; 
      var velocity : Vector3; 
             
      if(distFromPlayer.magnitude < 20){ 
         target = player.position; 
         velocity = distFromPlayer.normalized * speed; 
         velocity.y = -gravity; // Apply gravity
      } 
    
   rigidbody.velocity = velocity; 
   transform.LookAt(target); 

}

Note the ‘gravity’ will be constant (no acceleration) but should do the job if you just need your enemy to stick to the floor or travel downwards when they move off a cliff.

Thanks! That totally worked. I’m new to scripting and have relatively little idea what I’m doing so yeah…my code isn’t exactly elegant at this point.

My enemies bounce up and down like crazy when I use this or flip the gravity checkbox on.

Has anyone encountered this before?

I generally try not to directly modify rigidbody velocity, and with most of my enemies, using the built-in rigidbody gravity works for me. However in cases where I need to apply gravity manually (like my custom character controller) I generally do something like:

var gravity : float = 9.8;

function FixedUpdate(){
    rigidbody.AddForce(Vector3 (0, -gravity*rigidbody.mass, 0));
}