- Home /
Player Rotation
What im trying to do is make my character when ever he selects a enemy he rotates to face them this is my targeting script can you alter it so my character faces its selcted enemy.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Targeting : MonoBehaviour {
public 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;
PlayerAttack pa = (PlayerAttack)GetComponent("PlayerAttack");
pa.target = selectedTarget.gameObject;
}
private void DeselectTarget(){
if (selectedTarget){ // if any guy selected, deselect it
selectedTarget.renderer.material.color = Color.blue;
selectedTarget = null;
}
}
}
Im programming in C# Thanks in advance
What exactly doesn't work? Do the enemies change colour? Does your player attack them?
Ah, I see. I'd missed the "this is my targeting script can you alter it".
Answer by ardo314 · Mar 28, 2012 at 06:16 PM
You should take a look at sinus / cosinus
should look something like: a=|You.X - Enemy.X| b=|You.Y - Enemy.Y| c=sqrt(a²+b²)
d=arcsin(a/c) would be the direction you need to face.
Then you would need to do a animation where you substrac "1" from your current rotation till you have "d". This approach should work for right/left, up/down.
Attention: This may not be right, it's meant to be a guide on how to approach this.
Answer by clfischer · Mar 28, 2012 at 06:29 PM
In the Update function, where you select the new target, add the following line.
transform.LookAt(hit.transform);
This tells whatever your script is attached to to turn towards the object you just clicked. If the script isn't attached to the player but to something else, you should use player.transform.LookAt(hit.transform)
instead.
If you want the rotation to be smooth it'll take a few more lines of code using Lerp().