- Home /
Enemy LockOn and Shoot
Hi, I have these t Scripts that work well seperately but i cant combine them and make them work the same.
i want to when hit fire button actually lock on enemy and target which happens when seperate.
I would also like to have the lock remain on until i mous down elswhere.
Thanks
EnemyLockOn
var target: Transform; var rotationSpeed = 3; //speed of turning var myTransform : Transform; //current transform data of this enemy
function Update () { // check distance to target every frame: var distance = (target.position - myTransform.position).magnitude; var hit : RaycastHit;
if(Physics.Raycast(transform.position, transform.forward, hit, 100)
&& hit.transform.gameObject.tag == "Enemy")
var enemy = GameObject.FindWithTag("Enemy");
if(enemy != null)
if(Input.GetButton("Fire1")) {
transform.LookAt(hit.transform);
Debug.DrawLine(transform.position,target.position, Color.yellow);
//rotate to look at the player
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position),
rotationSpeed*Time.deltaTime);
}
}
and
IsTargeting
var isTargeting : boolean; var speed : float = 5;
function Update () { if(Input.GetButton("Fire1")) var enemy = GameObject.FindWithTag("Enemy");
if(enemy != null) {
var enemyLocation = enemy.transform;
transform.LookAt(enemyLocation);
}
}
Could you reformat the question and split the scripts in visible components? I have no idea what goes where like this and I'm sure the other people that want to see this question answered struggle aswell. Thanks in advance! (just use the edit option and the post-previewer to keep formatting clean)
Hi, I have a Player and as a child of the player i have 1 weapon object that has 4 weapon scripts that instantiate bullets and grenades that i can switch between using keys 1,2,3 & 4. I have put both of these scripts on the weapon object. What i am trying to do is on key down lock onto a target and fire at it but when i click elsewhere i break lock. Hope this makes sence. I am just playing with a few blocks to try to get the concept right as i am new to this.
Thanks
This code is terrible. In both scripts you declare the variable enemy in a narrower scope than where you try to access it. Why on earth are you calling GameObject.FindWithTag to find a GameObject tagged "Enemy" only when your raycast hit a GameObject tagged "Enemy"? You already have it so you don't need to go and find it.
I am very new at this and still got a long way to go, obviously. Thanks for the advice i will have a look. thats why i was trying to make one out of the 2.
Your answer
Follow this Question
Related Questions
lock ontro enemy 1 Answer
Locking onto Multiple AI's 1 Answer
Lock onto a target 1 Answer
Scripts Destroys all Objects its Attached to! 2 Answers
Enemies spawn on top of each other 2 Answers