Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Help with enemy AI

I'm trying to make it so the enemy will shoot out a raycast at the player, and if the player loses too much health, he dies. I already have the ai set up, but for some reason my shooting script isn't working. I tried to modify the shooting script from Brackeys raycast shooting tutorial.

Here's my script:

using UnityEngine;

using UnityEngine.AI;

public class EnemyShoot : MonoBehaviour

{

public float damage = 5f;

public float range = 1000f;

public float fireRate = 15f;

public float fireDistance = 100f;


public GameObject enemy;

public Transform playerObject;


// Start is called before the first frame update

void Start()

{

}


// Update is called once per frame

void Update()

{

float distance = Vector3.Distance(transform.position, playerObject.transform.position);


if(distance < fireDistance)

{

Shoot();

}

else

{


}

}


void Shoot ()

{


RaycastHit hit;

if (Physics.Raycast(enemy.transform.position, playerObject.transform.position, out hit, range))

{


Player player = hit.transform.GetComponent<Player>();

if (player != null)

{

player.PlayerDamage(damage);

}

}

}

}

Best Answer

  • MouledouxMouledoux Member
    Accepted Answer

    to get the direction from one vector to another is:

    Vector A --going to--> Vector B, is Vector B --minus-- VectorA


    Vector A in this case, would be: transform.position

    Vector B would then be: playerObject.position

Answers

  • on your last few lines, change


    Player player = hit.transform.GetComponent<Player>();


    to


    Player player = hit.GetComponent<Player>();


    You don't need a transform there. Also, your firerate isn't used in your script.

  • In the physics.Raycast the second parameter should be a direction not a position

  • how do i make the firerate used?

  • Did what @Dreek16designer said but now i get this error in the console.


    Assets/EnemyShoot.cs(42,33): error CS1061: 'RaycastHit' does not contain a definition for 'GetComponent' and no accessible extension method 'GetComponent' accepting a first argument of type 'RaycastHit' could be found (are you missing a using directive or an assembly reference?)

  • Also @JIMMY_VASHI04 how do I make it into a direction?

  • @Mouledoux so for the going to transition i would use Vector A.Vector B?

  • @Mouledoux NVM it works thank you!!!!!!

  • Thank you guys so much for the help!!!!!!

Sign In or Register to comment.