How do I make my Unity3d camera rotate around his following object? - unity3d

I'm making a game but I do not now how to let my camera rotate with the object he's following. (I did the follow part) Can somebody help me please. I'm using C#.

Please, can you describe what you actually want to do? What does "let my camera rotate with the object" mean?
If you want your camera to exactly follow the gameobject's rotation in a first person camera, you could achieve this by putting your camera as the gameobject's child.
You could also do this using the following code:
[SerializeField]
private Transform obj; //reference the gameobject's transform
void Update()
{
transform.rotation = obj.rotation;
}

You should use the transform.RotateAround to move the camera. This should be done inside the update method in your camera.
For example:
var target:transform;
function Update(){
//...
transform.RotateAround (target.position, Vector3.up, speed * Time.deltaTime);
}
For more information on the rotation method, see the docs.

If you want simple 3rd person camera, you can place camera as a child of your target object - the camera will "stick to it.
If you want to do this in code (for some reasons), something like this should work (attach script to GameObject with Camera component):
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
public Transform target; // Object to fallow. Select in Inspector
public Vector3 offset = new Vector3(0, 0, -10); // Offset to target
private GameObject container; // Container for our camera
void Start()
{
container = new GameObject("Camera Container"); // Create container (empty GameObject) for camera to avoid unnecessary calculations. It will follow the target object
transform.parent = container.transform; // Make this object child of container
}
//Update your camera follow script in LateUpade(), to be sure that 'target' movement is done
void LateUpdate()
{
//Check if target is selected
if (target == null)
return;
container.transform.position = target.position; // Set container position same as target
container.transform.rotation = target.rotation; // Set container rotation same as target
transform.localPosition = offset; // Move camera by offset inside the container
transform.LookAt(target); // Optionaly, force camera look at target object on any offset
}
}

Related

How to add a spawner on a side of moving camera in unity2D

I'm creating a 2D racing game in Unity2D and unsure how to approach on coding my spawner for objects e.g. power-up, rewards and obstacles ahead on the right side of my moving camera. The camera follows my vehicle and moves from left to right. Currently objects spawn in the game, but only spawn on a point and continue to spawn in the same point when the camera has scrolled way past. Apologies, if the answer was simple.
Here are the scripts I used:
coin.cs is attached to my coin prefab
public class coin : MonoBehaviour
{
public Camera mainCamera;
Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
mainCamera = GameObject.FindObjectOfType<Camera>();
rb = this.gameObject.GetComponent<Rigidbody2D>();
transform.position = new Vector2(mainCamera.pixelWidth / 32, getRandomHeight());
}
float getRandomHeight(){
return Random.Range(-(mainCamera.pixelHeight / 2) / 100, (mainCamera.pixelHeight / 2) / 100);
}
private void OnTriggerEnter(Collider coll){
if (coll.gameObject.tag == "Player"){
Destroy(this.gameObject);
}
}
// Update is called once per frame
void Update()
{}
}
and coinSpawner.cs is attached to a gameObject in the scene
public class coinSpawner : MonoBehaviour
{
float LastSpawnTime = -500f;
float NextSpawnTime = 3;
public Object CoinPrefab; // declare coinPrefab
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Time.time - LastSpawnTime > NextSpawnTime)
{
NextSpawnTime = Random.Range(3, 10);
LastSpawnTime = Time.time;
Instantiate(CoinPrefab);
}
}
Instantiate(CoinPrefab);
spawns this object without any information of position or parent object. This it will always be spawned at Scene root and 0,0,0.
Then this line
transform.position = new Vector2(mainCamera.pixelWidth / 32, getRandomHeight());
in coin always places it to the absolute position depending on your pixelWidth which doesn't change over time.
You are saying the Camera is moving so you should rather take it's transform.position into account.
You have basically two(three) ways to go here:
You can make the spawner GameObject a child of your Camera - so it is automatically moved along with it - and move it to the right to have the desired offset. Then simply spawn new objects at this GameObjects position. Then you can do it in coinSpawner:
Instantiate(CoinPrefab, transform.position, Quaternion.Identity);
Or get the Camera reference and use it's position + the desired offset either also only in coinSpawner like
// reference this already via the Inspector if possible
[SerializeField] Camera _camera;
// Otherwise get the reference on runtime
void Awake()
{
if(!_camera)_camera = Camera.main;
}
float getRandomHeight => Random.Range(-(_camera.pixelHeight / 2) / 100, (_camera.pixelHeight / 2) / 100;
and then do something like
Instantiate(CoinPrefab, new Vector2(_camera.transform.position.x + mainCamera.pixelWidth / 32, getRandomHeight()), Quaternion.Identity);
This would actually be more efficient since the entire coin script would be reduced to only the OnTriggerEnter part and not every coin would use FindObjectOfType and GetComponent when spawned.
Basically the same as above but sticking to your code structure simply do
transform.position = new Vector2(mainCamera.transform.position.x + mainCamera.pixelWidth / 32, getRandomHeight());
I wouldn't do it this way though due to efficiency as said.

Camera follow player around planet

I have a planet and a player moving on it using gravity. I would like to have a camera to follow the player around it. Using the Parent Constraint component works perfectly, but I want to delay the rotation follow, so I have to use a script. I just cannot figure out how to make it follow it around the globe. I either have a camera that completely freaks out, or a camera that sort of follows the player but doesn't move over the planet and always stays in front of it. And often the position following works, but as soon as I add something that changes rotation it only does that. I've tried many different scripts but nothing works. I'm grateful for any help.
EDIT
I'm sorry for not adding an example. At the moment I've tried this script attached to the camera:
public class CameraFollow : MonoBehaviour
{
public GameObject player;
private Vector3 offset;
void Start()
{
offset = transform.position - player.transform.position;
}
void LateUpdate()
{
transform.rotation = Quaternion.Slerp(transform.rotation, player.transform.rotation, 50f * Time.deltaTime);
transform.position = player.transform.position + offset;
}
The camera does mimic the rotation of the player, but the position isn't being follow correctly anymore. It seems mostly stuck in place, moving only very slightly.
In order to have a camera following a GameObject, you need to go to the camera you want following the GameObject, select Add component, write FollowPlayer, press New script, and then press select and add. Edit the script so it contains the following:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowPlayer : MonoBehaviour
{
public Transform player;
public Vector3 offset;
// Update is called once per frame
void Update()
{
transform.position = player.position + offset;
}
}
Then, you will need to drag and drop the GameObject you want the camera to follow, in the "Player" box.
Define the offset of the camera from the GameObject, and your'e good to go.

Unity3D follow Sphere player camera rotation

Hi I'm trying to get my camera to follow my player (Sphere) when ever it moves around. I have got the camera to follow the player, but when the sphere spins, so do the camera. That is not what i'm looking for. I need the camera to stay put on the sphere and rotate when I turn. This is my code so far:
EDIT: What I'm looking for is something like you see in the vid. where the camera rotate when the sphere is turning, so it's behind it all the time. https://www.youtube.com/watch?v=jPAgPQi1l0c
using UnityEngine;
using System.Collections;
public class TransformFollower : MonoBehaviour
{
[SerializeField]
private Transform target;
[SerializeField]
private Vector3 offsetPosition;
[SerializeField]
private Space offsetPositionSpace = Space.Self;
[SerializeField]
private bool lookAt = true;
private void Start()
{
offsetPosition = new Vector3(-3, -2, 0);
}
private void Update()
{
Refresh();
}
public void Refresh()
{
if (target == null)
{
Debug.LogWarning("Missing target ref !", this);
return;
}
// compute position
if (offsetPositionSpace == Space.Self)
{
transform.position = target.TransformPoint(offsetPosition);
}
else
{
transform.position = target.position + offsetPosition;
}
// compute rotation
if (lookAt)
{
transform.LookAt(target);
}
else
{
transform.rotation = target.rotation;
}
}
}
You should implement the following logic:
Create an empty gameObject:Character, where it will have as childs: Camera, Sphere
when you move, you simply transform the Character, so the Camera and the Sphere transform in the exact same way.
Now, when you want to rotate only the Sphere, but not the camera, just apply your rotation(or anything else), only in the sphere.
To do so, in your script you can pass the Character and the Sphere.
So moving transformations will be applied in on the Character and any custom move, only in the sphere.
Nik
Did you write this code yourself?
It simply seems that if lookat is true, it will do what you want. If it is false, if will do what you describe.
Just look in the editor and check the 'look at' box.
If you never want to use it you can remove it from the code by removing the lookat variable and replacing
// compute rotation
if (lookAt)
{
transform.LookAt(target);
}
else
{
transform.rotation = target.rotation;
}
by
// compute rotation
transform.LookAt(target);
EDIT more explanation:
In your code, you have two options: lookat and offsetPositionSpace.
Basically, offsetPositionSpace can be two values:
Self -> The camera will always be behind the player (if you rotate the player, it moves to stay behind
World -> The camera will always imitate the player's moves (If the player rotates, the camera won't move
LookAt can also have two values
true -> the camera looks at the player, always
false -> the camera imitate the players rotation (if the player rotates, the camera does the same and stops looking at the player)

How do i replace my game object's current position with a new one?

I wanted to make a vertically scrolling background with 3D assets (2D pictures works fine, but i wanted the cool lighting effect), and i kept failing doing something i though would be so simple.
so here's my current progress:
public Vector3 target;
private Transform Top_Top_Left_Rescroll;
void Start (){
target = GameObject.FindGameObjectWithTag ("Top_Top_Left_Rescroll").GetComponent<Transform>();
}
void Update () {
if (gameObject.transform.position.y <= -12) {
gameObject.transform.position = new Vector3 (target.x, target.y, target.z);
}
}
}
The object resets it's position to 0 after the if statement (the rotation and scale weren't affected), and i ran out of ideas to do what i want.
You are passing a Transform to a Vector3.
try :
target = GameObject.FindGameObjectWithTag("Top_Top_Left_Rescroll").transform.position;
ps: I'm not sure if you really want your target position to never change, but you are passing it's value during Start() so you will always place your gameObject in every frame at the same initial position.

Drag and Drop between 2 gameObjects

I have 2 Spheres in my scene. I want to be able to drag and drop my mouse from one sphere to the other, and have an indicator (a straight line for example) while dragging. After releasing the mouse button, I want to store in the first sphere the other sphere (as GameObject).
I need this in UnityScript, but I can accept C# ideas.
So far I have thought about onMouseDown event on the first Sphere, and then onMouseEnter to the other sphere, I'll store the data in some global variable (which I donno how to do yet) and in case of onMouseExit I'll just put the global variable as null.
Then onMouseUp on the first Sphere I'll store the global variable in the pressed object (the sphere).
Any tips and tricks on how to do it?
Assumptions/Setup
You're working in a 2D worldspace; the logic for dragging the object for this part of the solution would need changing.
Setting parent after click drag, referred to setting the object you didn't click to be the child of the parent you did click on.
The camera should be an orthographic camera; using a perspective camera will cause the dragging to not align with where you think it should be.
In order to make the dragging work, I created a quad that was used as the 'background' to the 2D scene, and put that on a new layer called 'background'. Then setup the layermask field to only use the background layer.
Create and setup a material for the line renderer, (I'm using a Particles/Additive shader for the above example), and for the parameters of the line renderer I'm using Start Width: 0.75, End Width: 0, and make sure Use World Space is ticked.
Explanation
Firstly setup the otherSphere field to be pointing to the other sphere in the scene. OnMouseDown and OnMouseUp toggle the mouseDown bool, that is used to determine if the line renderer should be updated. These are also used to turn on/off the line renderer, and set/remove the parent transform of the two spheres.
To get the position to be dragged to, I'm getting a ray based off of the mouse position on screen, using the method ScreenPointToRay. If you wanted to create add smoothing to this drag functionality, you should enable the if (...) else statement at the bottom, and set the lerpTime to a value (0.25 worked well for me).
Note; when you release the mouse, the parent is immediately set, as such both objects end up getting dragged, but the child will return to it's former position anyway.
[RequireComponent(typeof(LineRenderer))]
public class ConnectedSphere : MonoBehaviour
{
[SerializeField]
private Transform m_otherSphere;
[SerializeField]
private float m_lerpTime;
[SerializeField]
private LayerMask m_layerMask;
private LineRenderer m_lineRenderer;
private bool m_mouseDown;
private Vector3 m_position;
private RaycastHit m_hit;
public void Start()
{
m_lineRenderer = GetComponent<LineRenderer>();
m_lineRenderer.enabled = false;
m_position = transform.position;
}
public void OnMouseDown()
{
//Un-parent objects
transform.parent = null;
m_otherSphere.parent = null;
m_mouseDown = true;
m_lineRenderer.enabled = true;
}
public void OnMouseUp()
{
//Parent other object
m_otherSphere.parent = transform;
m_mouseDown = false;
m_lineRenderer.enabled = false;
}
public void Update()
{
//Update line renderer and target position whilst mouse down
if (m_mouseDown)
{
//Set line renderer
m_lineRenderer.SetPosition(0, transform.position);
m_lineRenderer.SetPosition(1, m_otherSphere.position);
//Get mouse world position
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out m_hit, m_layerMask))
{
m_position.x = m_hit.point.x;
m_position.y = m_hit.point.y;
}
}
//Set position (2D world space)
//if (m_lerpTime == 0f)
transform.position = m_position;
//else
//transform.position = Vector3.Lerp(transform.position, m_position, Time.deltaTime / m_lerpTime);
}
}
Hope this helped someone.