- Home /
2d platformer combat system
I'm making a 2d platformer and I have a character that has a sword. I want to be able to have the enemy hit you when he collides with you and you take health from him when he collides with the sword. Now the thing is, my sprite has the sword sticking out so I can't have a separate gameobject to detect collisions between the sword and enemy. Would the best way be to have the enemy have a raycast and use collisions to take damage or raycast for both? If so, how would I go about making the knockback for the player? I tried doing it with the collision but when the player touches the enemy nothing happens. I think it has something to do with the collision seen has it doesn't remove anything from health. Any help would be greatly appreciated! Thanks!
using UnityEngine;
using System.Collections;
public class CombatSystem : MonoBehaviour {
public CharacterController controller;
public int health = 50;
public float knockbackX = 20F;
public float knockbackY = 1F;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (health <= 0){
Application.LoadLevel("Main Menu");
}
}
void onControllerColliderHit(ControllerColliderHit hit){
if (hit.gameObject.tag == "Enemy"){
health -= 10;
controller.Move(new Vector2(-knockbackX, knockbackY));
}
}
}
Answer by boriswc97 · Sep 07, 2013 at 11:16 AM
Do the following thing, create a new gameobject, Cube, and adjust it to fit the sword, tag it Sword or something like that, and delete the component of the cube "Mesh Renderer". After that create another script to the sword that when he collides with the enemy and you press "Attack Button", it will send a message to the enemy to receive the damage, and you will use the GetComponent to your script where your character's health is, and make his heath go +(Number of lifesteal). Hope that helped