So, I ran into a problem with using physics, which is always something that seems to bring up problems.
I have a simple 2d scene with a player that can move left and right, and an enemy object that moves in from the right (starts off-screen and continual moves to the left). I was successful in adding a working attack function for the player, where when the player clicks, all enemies in range will take damage and be knocked in the opposite direction to which the player is on. That worked fine.
I then moved to apply the same thing on my player, where as when they get hit by the enemy they should be knocked back. Except, when I tested it, when the player object came in contact with the enemy, instead of moving in the opposite direction (which would be to the left), it moved down. This is the script I have attached to my player's hitbox trigger gameobject, which is a parent of the player game object.
public int playerHealth;
private Rigidbody2D rb2d;
private GameObject enemyObj;
public int knockbackForce;
public float knockTime;
private GameObject playerObj;
void Start(){
playerObj = GameObject.FindGameObjectWithTag ("Player");
rb2d = GameObject.FindGameObjectWithTag ("Player").GetComponent ();
}
void OnTriggerEnter2D (Collider2D collider){
if (collider.gameObject.layer == LayerMask.NameToLayer("Enemy")) {
enemyObj = collider.gameObject;
int Enemydamage = collider.gameObject.GetComponent ().damage; //lets just say that it's 1 for the sake of simplicity
TakeDamage (Enemydamage);
}
}
public void TakeDamage(int damage){
playerHealth -= damage;
rb2d.isKinematic = false;
Vector2 difference = (playerObj.transform.position - enemyObj.transform.position); //first transform is of thing being knocked back, second transform is of thing applying force
difference = difference.normalized * knockbackForce;
rb2d.AddForce (difference, ForceMode2D.Impulse);
StartCoroutine (KnockCo (rb2d));
}
private IEnumerator KnockCo(Rigidbody2D playerRb2d){
if (playerRb2d != null) {
yield return new WaitForSeconds (knockTime);
playerRb2d.velocity = Vector2.zero;
playerRb2d.isKinematic = true;
}
}
I have no idea why this is happening and any help would be very much appreciated.
↧