Home > Blockchain >  Turning the character towards the camera
Turning the character towards the camera

Time:07-21

This script is on the character. When the character starts to move, his face turns towards the camera.
This code needs to be redone so that the character always looks towards the camera, even if he is standing still.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TPM : MonoBehaviour
{
   CharacterController controller;
   public Transform cam;

   public float speed = 6f;

   public float turnSmoothTime = 0.1f;
   float turnSmoothVelocity;

   private void Start()
   {
      controller = GetComponent<CharacterController>();
   }

   private void Update()
   {
      float horizontal = Input.GetAxis("Horizontal");
      float vertical = Input.GetAxis("Vertical");
      Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;

      if(direction.magnitude >= 0.1f)
      {
         float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg   cam.eulerAngles.y;
         float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
         transform.rotation = Quaternion.Euler(0f, angle, 0f);

         Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
         controller.Move(moveDir.normalized * speed * Time.deltaTime);
      }
   }
}

CodePudding user response:

use transform.LookAt(Camera.main.transform.position) in your Update.

CodePudding user response:

Here is a suitable solution I found

   public Transform cam;
   public float speed = 5f;

   private void FixedUpdate()
   {
         transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(0f, cam.rotation.eulerAngles.y, 0f), speed * Time.deltaTime);
   }
  • Related