Enemy sinks into ground

Ok, I made a script that contained gravity, to replace rigidbody gravity, but when I use it the enemy falls as usual then flickers through the terrain, here’s the code:

private var gVelocity : float;
private var counter : float;
private var collisionFlags : CollisionFlags; 
var target : Transform;
var vel_vec : Vector3;
var speed : float;
var distance_byte : float;
var player_life : player_life_script;
private var moveDirection:Vector3 = Vector3.zero;
var gravity:float = 20.0;
var TerrainTag : String;
var Grounded : boolean;

private var startpoint : Vector3;
private var endpoint : Vector3;

function Awake()
{
	counter = 0;
	gVelocity = 0;
	Grounded = false;
}

function Update()
{

	//Apply gravity
	
	if (Grounded == false)
	{
		gVelocity += gravity * Time.deltaTime;
		moveDirection.y -= gVelocity;
	}
	else
	{
		gVelocity = 0;
		moveDirection = Vector3.zero;
	}

	vel_vec = target.position - transform.position; // creates the vector from the enemy to you.
	
	startpoint = Vector3(transform.position.x,transform.position.y,transform.position.z);
	endpoint = Vector3(target.position.x,transform.position.y + moveDirection.y,target.position.z);
	
	
	transform.LookAt(Vector3(target.position.x, transform.position.y, target.position.z)); // enemy looks to you
	if (!animation.IsPlaying("Attack"))
	{
		transform.position = Vector3.Lerp (
		startpoint, endpoint,
		Time.deltaTime * 1);
		//transform.Translate(Vector3.forward * speed * Time.deltaTime); // enemy walks to you
	}
	
	
	if (vel_vec.magnitude <= distance_byte && !animation.IsPlaying("Attack")) //if is near
	{
		animation["Attack"].wrapMode = WrapMode.Once;
		animation.CrossFade("Attack");
		player_life.animation.CrossFade("GetHit");
		--player_life.hp;
		vel_vec = Vector3.zero;
		if (!animation.IsPlaying("Attack"))
			animation.CrossFade("Default Take");
	}
	else if (vel_vec.magnitude > distance_byte + 5) // if is far
		animation.CrossFade("Walk");
}



function OnCollisionEnter (hit : Collision)
{
	if (hit.gameObject.tag == TerrainTag)
	{
		Grounded = true;
	}
	else
	{
		Grounded = false;
	}
}

The enemy has a box collider and rigidbody. on the rigidbody the x and z axis is locked for rotation, and gravity is disabled. thanks :slight_smile:

You’re mixing up rigidbody physics and transform movement. Either do one, or the other- don’t do both. If you have your own physics engine (for gravity), manage collision detection with raycasts and get rid of the rigidbody entirely.

Ok thanks, the only reason I used this code was because rigidbody gravity was going wrong, but i fixed it, thanks anyway :slight_smile: