- Home /
Making enemies push player back.
Hi all, I am a beginner in unity programming, and I'm currently making a parkour game. I want to make the enemies move towards player, and push him back. I have a c# script, which makes the enemies rotate to see the me, then move to me. It looks like this: using UnityEngine; using System.Collections;
public class EnemyAI : MonoBehaviour {
Transform target; //the enemy's target
float moveSpeed = 3f; //move speed
float rotationSpeed = 3f; //speed of turning
Transform myTransform; //current transform data of this enemy
void Awake()
{
myTransform = transform; //cache transform data for easy access/preformance
}
void Start()
{
target = GameObject.FindWithTag("Player").transform; //target the player
}
void Update () {
//rotate to look at the player
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
//move towards the player
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
}
I got it from another thread on this forum, but the enemies just approach me and the rotate around me. So, I want to make them push me back. Is there a way to do this (I use the standard 1st person controller and the enemies are cubes, with box colliders. Also, I'd prefer c#, because i started programming with this language.
You need to use something like OnCollisionStay() and have the enemy identify that it collides with you, then it can affect your position until you are not colliding with it -
http://docs.unity3d.com/Documentation/ScriptReference/Collider.OnCollisionStay.html
If the player is using a CharacterController, you will need to use OnControllerColliderHit() in the script attached to the player.
I am happy to see that you are trying to solve my problem, but I need to know exactly how to move the player.
Answer by CJGames · Dec 11, 2014 at 11:22 PM
Do your enemies have rigidbodys? Cuz if they have, just make sure they don't stop walking forward when they reach the player and they push it autamatically...At least this happens in my game :D
Your answer
Follow this Question
Related Questions
Player Knockback / PushBack 2 Answers
2D dash/knockback? 1 Answer
Push player in direction based on objects movement 1 Answer
Why is my push rigidbody script not effected by mass? 2 Answers
Unity LocalNotification AlertImage 0 Answers