- Home /
Create a vector between me and my enemy.
Hello everyone, i'm working on a plane game and i want my enemy to attack me when is a certain distance from me, since i'm shooting bullets as well i can't use a sphere trigger collider around me because my bullets hit that collider so i was thinking using a vector traced from my enemy position to me and everytime it was shorter than a certain distance it would start shooting me. The question is, how do i create this vector keeping it updating?
I'm using this condition to shoot:
var bulletPrefab: Transform;
var bulletSpeed = 60;
var nextShotTime : float = 0.0;
var timeBetweenShots : float = 2.0;
//var shootSound: AudioClip;
function Update()
{
if (***********)) //this is where my vector condition would enter
{
// Shoot();
if (nextShotTime <= Time.time)
{
Shoot();
nextShotTime = Time.time + timeBetweenShots;
}
}
}
function Shoot()
{
var shoot = Instantiate(bulletPrefab,GameObject.Find("Spawn").transform.position,GameObject.Find("Spawn").transform.rotation);
shoot.rigidbody.AddForce(GameObject.Find("Spawn").transform.forward * bulletSpeed);
// AudioSource.PlayClipAtPoint(shootSound, GameObject.Find("Spawn").transform.position);
}
Can you guys help me out with this, doesn't seem very complicated but i really can't figure it out... Thanks everyone.
Answer by robertbu · Feb 15, 2013 at 02:33 PM
I assume this is the enemy script. You need the game object of the player (or the transform). Typically you would get this once at Start();
var goPlayer : GameObject;
function Start() {
goPlayer = GameObject.Find("Player");
//alternate goPlayer = GameObject.FindWithTag("Player");
}
Then in update you can test the distance:
if (transform.position - goPlayer.transform.distance).magnitude < someValue) {
// Shooting stuff
}
There's a built-in distance function here: http://docs.unity3d.com/Documentation/ScriptReference/Vector3.Distance.html
Performance optimization - use:
if (transform.position - goPlayer.transform.distance).sqr$$anonymous$$agnitude < (someValue * someValue))
Getting the magnitude relies on finding the square root (see: Pathagorean Theorem), and square root computations are much more computationally expensive than multiplication. If you use a squared magnitude ins$$anonymous$$d, the square root computation never happens. However, you must square 'someValue' to adjust the equation.
i went with
if (transform.position - goPlayer.transform.position).magnitude < someValue)
and it worked eally well XD
Your answer
Follow this Question
Related Questions
Why this script is not working? 1 Answer
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
enemy shoots with animation 1 Answer
Disable & Re-enable Script 1 Answer
Script Conversion JS to C# 3 Answers