Camera to follow one object and rotate towards another
Hi,
I am new to Unity and do not have much coding experience, so please bare with me. I am basically trying to do some cut-and-paste coding to achieve a small proof-of-concept where the camera is following one object (player1) but rotates based on the position of another (player2).
What I have now is a Main camera as a child to player1 which takes care of the following, but how can I rotate the camera around player1 based on the direction of where player2 is?
I have tried various things such as a lookAt target for the Main camera, or having the player1 and player2 always facing eachother, and even if the rotation works it always seems to override the following of player1.
You could think of this being a 3rd person game where player1 has an "auto aim" targeting player2. I.E player2 should always be straight to the left of player1 regardless of its position.
(right now I am just using two capsules on a plane)
Hope this makes some sense, otherwise I apologize.
Thanks!
Answer by Cynikal · Nov 03, 2016 at 11:51 AM
Since the camera is a child, it will follow player 1.
To have it look at another object, in your Update() put:
transform.LookAt(Player2?);
The camera will face player 2 at all times.
Thank you for the response. I believe I tried this but that it did not then rotate around Player1, as it is actually should be looking at player 1, but from different angles based on the direction of player2.
Sorry if im confusing you. Will give this another go nonetheless
Give me a little bit, i'll try to come up with a script for you.
using UnityEngine;
public class UnityAnswersHelp : $$anonymous$$onoBehaviour
{
public Transform EnemyPlayer;
private Transform myCamera;
public float CameraTurnSpeed = 5f;
void Start()
{
myCamera = transform.FindChild("$$anonymous$$ain Camera");
}
private Vector3 _offset;
void Update()
{
if (EnemyPlayer) //We have a EnemySelected.
{
Vector3 targetDir = EnemyPlayer.position - transform.position;
float step = CameraTurnSpeed * Time.deltaTime;
Vector3 newDir = Vector3.RotateTowards(transform.forward, targetDir, step, 0.0F);
Debug.DrawRay(transform.position, newDir, Color.red);
transform.rotation = Quaternion.LookRotation(newDir);
}
}
}
I tested it. Seems to work.
Your answer
Follow this Question
Related Questions
viewing on the Mouse Y axis not working. 0 Answers
getting Jittery movement on camera when player rotating and moving in same time 0 Answers
CineMachine Camera Movement is inverse 1 Answer
(Solveed) How to make object face same direction as its parent? 0 Answers
Trying to Make a Smooth Camera Zoom While Changing Targets 1 Answer