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 =;
        PlayerAttack pa = (PlayerAttack)GetComponent("PlayerAttack"); = selectedTarget.gameObject;

    private void DeselectTarget(){
        if (selectedTarget){ // if any guy selected, deselect it
            selectedTarget.renderer.material.color =;
            selectedTarget = null;

Im programming in C# Thanks in advance

You should take a look at sinus / cosinus

should look something like:
a=|You.X - Enemy.X| b=|You.Y - Enemy.Y|

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.

In the Update function, where you select the new target, add the following line.


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().