- Home /
lookat wont track target
Hi community, im trying to do this without asking for help, but am really struggling getting my player to keep looking at target when clicked. it looks at target, but when I move it stops looking, im tryin to keep it locked until either target destroyed or when deselect. any hint or tips would be apprieciated as I've been stuck for over a day and can find nothing on forum about problem. thanks
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Targeting : MonoBehaviour {
private Transform selectedTarget;
void Update(){
if (Input.GetMouseButtonDown(0)){ // when button clicked...
RaycastHit hit; // cast a ray from mouse pointer:
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
// if enemy hit...
if (Physics.Raycast(ray, out hit) && hit.transform.CompareTag("Enemy")){
DeselectTarget(); // deselect previous target (if any)...
selectedTarget = hit.transform; //set the new one...
SelectTarget(); // and select it
}
}
}
private void SelectTarget(){
selectedTarget.renderer.material.color = Color.red;
transform.LookAt(selectedTarget.transform);
}
private void DeselectTarget(){
if (selectedTarget){ // if any guy selected, deselect it
selectedTarget.renderer.material.color = Color.blue;
selectedTarget = null;
}
}
}
I'm still stuck, ive added a variable called..
public bool Lockview = false;
and wrote under selectTarget in update...
Lockview = true; transform.LookAt(selectedTarget.position);
when I click on object it targets and ticks the bool box in inspector, so it sum kinds of works. but I still cant get to keep my player object facing the target I click and stay faced till I click another object. sort of like a lock
Answer by Dracorat · Nov 18, 2013 at 08:42 PM
You'll need to do the LookAt
in the Update
method. Thus, just create a boolean for something like bool lockView = false;
- set it to true when the target is selected. In the Update
, check if it's true and if so, LookAt
.