How can i make a Enemy Shoot Script?

So, i want a enemy shoot script for my game that does something like, when you are 20 meters away it starts shooting at you and just stands still or walks towards you. Is that a possibility? If you ansker with a link: I have looked at a lot of stuff and didn’t find anything

1 Like

All you have to do is calculate the distance between the player and the enemy, when distance<=20 then you call an Attacking function. Example :

var Player : Transform;
var enemy : Transform;
var IsAttacking : boolean = false;
var Bullet : Rigidbody;
var SpawnPoint : Transform;
var Distance : Vector3;
var DistanceFrom : float;
var fireRate = 0.5;
var nextFire = 0;

function Update(){
Attacking();

// Calculate the distance between the player  the enemy

Distance = (enemy.position - Player.position);
Distance.y = 0;
DistanceFrom = Distance.magnitude;
Distance/=DistanceFrom;

// If the player is 20m away from the enemy, ATTACK!

if(DistanceFrom<20){
IsAttacking = true;
}
else{
IsAttacking = false;
}
}

function Attacking(){
if(IsAttacking){

// The enemy isn't blind so it should face the player 

enemy.LookAt(Player);

//Shoot

if(Time.time > nextFire){
nextFire = Time.time + fireRate;

var Shoot = Instantiate(Bullet,SpawnPoint.position,SpawnPoint.rotation);
Shoot.AddForce(SpawnPoint.forward*5000);
}
}
}
1 Like

You won’t find answers to such broad questions. If you want to program things, you have to break your problem up in small chuncks and try and find sollutions for each of those chuncks.

1 Like

Intense_Gamer94, your script dosen’t work, i think the one i wrote yesterday works pretty well :slight_smile:

var projectile : Rigidbody;

var speed = 10;

var player : Transform;

var shotS : AudioClip;


function Start() {
    var rendum = Random.Range(1F,3F);
    InvokeRepeating("Shuut", 2, rendum);
}

 

function Update() {
    transform.LookAt(player);
}

function Shuut () {

audio.PlayOneShot(shotS);

clone = Instantiate(projectile, transform.position, transform.rotation);
clone.velocity = transform.TransformDirection( Vector3 (0, 0, speed));

Destroy (clone.gameObject, 0.5);
}
1 Like

with each of the scripts i get parsing error how do i fix it

I adapted the script to my needs and it looks like this

using System.Collections;

public class BotNormalShooting : MonoBehaviour {

    public Transform player;
    public float range = 50.0f;
    public float bulletImpulse= 20.0f;

    private bool onRange= false;

    public Rigidbody projectile;

    void Start(){
        float rand = Random.Range (1.0f, 2.0f);
        InvokeRepeating("Shoot", 2, rand);
    }

    void Shoot(){

        if (onRange){

            Rigidbody bullet = (Rigidbody)Instantiate(projectile, transform.position + transform.forward, transform.rotation);
            bullet.AddForce(transform.forward*bulletImpulse, ForceMode.Impulse);
         
            Destroy (bullet.gameObject, 2);
        }


    }

    void Update() {

        onRange = Vector3.Distance(transform.position, player.position)<range;

        if (onRange)
            transform.LookAt(player);
    }
 

}

Thanks for the help… see ya!

5 Likes

but when im back in unity what should i put on the projectile variable? i can’t put my bullet prefab… so what can i put in?

Even though this thread is super ancient I’ll answer your question.

Projectile is a Rigidbody, so you can only drag Rigidbody components into it. Unity is smart enough to know when you drag a prefab or GameObject into a slot to look and see if it has the component required in the destination slot. Unfortunately your Projectile Prefab does not have a Rigidbody which is what goes in that slot so it says “no, you cannot put this here - it does not fit.”

I suggest starting here before you bite off more than you can chew and get overwhelmed.

ok and 1 more question, why when im using transform.LookAt it immediately makes the gameobject with this script to disappear, does anyone know why?

Try an alternate form of what you’ve got, something like this -

public GameObject playerObj;
//^ Drag the player object from heirarchy
//             into this field in inspector

void Update() {
        if (onRange) {
            transform.LookAt(playerObj.transform.position);
        }
    }

tried, for some reason still makes whoever has the script with this line of code disappear :confused:

Strange. I don’t know what to tell you, but someone else will come along and help hopefully. :\

can it be because i’m doing a 2d game or it doesn’t matter? thanks alot for the help anyway :smile:

Oh. Yeah, that’s an issue. You might be rotating the object so it’s edge on with the camera.

ohh so that they are on the same line and the camera cant see it… so can i do something to fix it?

The reason you don’t use that method specifically is because the face that shows the sprite is the thing pointing at the player object. Try adding certain transform rotations to the object.

//something like this maybe?

transform.LookAt(playerObj.transform.position);
transform.Rotate(transform.right);//try other rotations as well like forward and up

Mind copypasting the whole C# code file? I’d like to take a look.

this issue happened on my main game so i created a new one just to test and try to fix it there, so i only have 2 objects and the script attached to one of them

transform.position = Vector3.MoveTowards(transform.position, Player.transform.position, 0.04f);

use this line of code instead of transform.lookat
2d games works good with transform.movetowards

this script can help in some cases but in a slightly more realistic game you will need raycasts so can you post a one using raycasts. it is because I already use a ray cast method for the player in my FPS game. here is a link to my video not on the FPS but has a clip from it in the start.
the link -:

Please don’t necro-post. If you have a new question, make a new post. It’s FREE!!

How to report your problem productively in the Unity3D forums:

http://plbm.com/?p=220

This is the bare minimum of information to report:

  • what you want
  • what you tried
  • what you expected to happen
  • what actually happened, log output, variable values, and especially any errors you see
  • links to actual Unity3D documentation you used to cross-check your work (CRITICAL!!!)

The purpose of YOU providing links is to make our job easier, while simultaneously showing us that you actually put effort into the process. If you haven’t put effort into finding the documentation, why should we bother putting effort into replying?