- Home /
Selecting a specific target with a 2D raycast
Hello! This is my first time posting here, but I'm really at a loss.
So. First my code for now:
My attack script:
private void Attack()
{
if (Physics2D.Linecast(johnBody.position, johnLeftArm.position, 1 << LayerMask.NameToLayer("Enemy1")) && turnedLeft == true)
{
Debug.Log("hit");
Enemy1Health enemy1hp = (Enemy1Health)target.GetComponent("Enemy1Health");
enemy1hp.adjustCurrentHealth(-meleeDamage);
Debug.Log(enemy1hp.currentHealth);
}
if (Physics2D.Linecast(johnBody.position, johnRightArm.position, 1 << LayerMask.NameToLayer("Enemy1")) && turnedRight == true)
{
Debug.Log("hit");
Enemy1Health enemy1hp = (Enemy1Health)target.GetComponent("Enemy1Health");
enemy1hp.adjustCurrentHealth(-meleeDamage);
Debug.Log(enemy1hp.currentHealth);
}
}
And then my enemy health script:
void Update ()
{
adjustCurrentHealth(0);
}
public void adjustCurrentHealth (int adjust)
{
currentHealth += adjust;
if (currentHealth < 1)
{
currentHealth = 0;
Destroy(gameObject);
}
if (currentHealth > maxHealth)
{
currentHealth = maxHealth;
}
}
What is happening is that whenever the 2D raycast hits an enemy, the enemy looses health. BUT! it's not the specific enemy that looses health, it's just the enemy overall. (for example, if the enemy you hit is down to 0 health, ALL of the enemies have 0 health). So I think the answer would be to find the specific target that the raycast is hitting, and adjusting its health. But since I'm really new to using the 2D raycasting, I have to ask you all for help.
I'm not getting the target, other than:
public GameObject target;
And then dragging the enemy down to the public GameObject. That is where the problem is.
Thank you!
... also, if I'm missing something, just tell me and I'll post it.
Answer by Quaker_SDR · Sep 01, 2014 at 11:32 AM
Enemy1Health enemy1hp = (Enemy1Health)target.GetComponent("Enemy1Health");
From where you getting the target?
See that's the thing, I'm not getting the target, other than:
public GameObject target;
And then dragging the enemy down to the public GameObject. That is where the problem is.
Physics2D.Linecast will return RaycastHit2D
RaycastHit2D target;
target=Physics2D.Linecast(johnBody.position, johnLeftArm.position, 1 << Layer$$anonymous$$ask.NameToLayer("Enemy1"));
Thank you, I think this is enough for me to go on. I can't believe the answer was that simple!
Your answer
