How to make the camera follow the player in unity - c#

Hey i am making a unity game called Cube-Runner. There is a cube and obstacles and you have to go between them. Not going into the game a lot but the problem is how to follow the player. I can't parent it as if i do that while the cube falls the camera will also move with the rotating cube and will make the player(At least myself) dizzy.
Please give me a script
There needs to be a offset Vector3 which i can change from the inspector.
The offset Vector3 may work.
It should be written in C#.
NOTE: I AM NEW TO C# AND UNITY DO NOT JUDGE BY QUESTION

if you dont want to make the player the parent of the camera, then you can do this :
Create a C# script called CameraMovement and attach it to the camera
add this to CameraMovement
using UnityEngine;
class CameraMovement : MonoBehavior
{
public Transform player;
public Vector3 offset;
void Update()
{
//get the players position and add it with offset, then store it to transform.position aka the cameras position
transform.position = player.position + offset;
}
}
click on the camera and look at the inspector, you should see that there is a script called CameraMovement and 2 fields : player and offset. assign player with your player (drag and drop) and offset with the relative position between your camera and the player (where the camera is with the player being the center).
and you're done, play the game and see the results

You could try using the cinemachine tool, it will make you camera follow smoothly to the player. You could check any tutorial on youtube but I recommend you to check the one "Brackeys" did. No code needed for cinemachine

Related

When animating a 2d object `Transform.Translate()` stops working

I'm developing an enemy AI in a 2D Game that I'm working on. This enemy swims and I wanted to make a "floating effect" animation for the enemy, so I made an animation where the Y Axis of the game object bounces up and down.
I Use transform.Translate() to move the enemies in the game and it worked just fine until I made this animation. But, when the animation is playing, the enemy can't move in any direction.
public virtual void Move(float speed)
{
if (canMove)
{
transform.Translate(new Vector2(speed, 0) * Time.deltaTime);
}
}
Once you have a keyframe in any state of your animator for a certain property the animator will always overrule any changes done in a script because the animation updates are all done after Update. You could try to either move your code to LateUpdate.
Or in your specific case you do not want the x component of your position keyframed at all. Simply remove all the keyframes for the x (and z) component(s) of the position from the animations so only y has keyframes. This should solve your problem.
Alternatively use your movement script on a GameObject on a higher level in the hierachy as your Animator - meaning add a new GameObject, make the animated object a child of it and place your movement script instead on that parant object.

Changing player rotation to a camera rotation

I'm new to unity and I'm currently working on a portal-like game.
I did the whole teleportation script and it works, but the problem comes that I didn't implement the player camera correction and actually I don't have any ideas how to do it. The concept is that when you're jumping through a portal, the player (or player camera) rotation should be changed to the portal/portal camera rotation from you've come so the final effect is more 'realistic'.
I've tried some lines in teleportation script like player.transform.rotation = portal.transform.rotation but in the end it didn't work and now I end up with nothing, deleting previous scripts and trying to write it all over and over again.
I'll be glad if someone could guide me how to start coding it. Should I do it in onTriggerEnter (when you're jump through portal), or in onTriggerExit? Should the script be attached to a player or to a portals? Should I gather rotation only from camera or from the whole gameobject (portal/player)? I'm posting also couple of screens (with a video how it currently works, and also an entire teleportation script. If I missed something just ask me and I'll post it here.
https://imgur.com/a/pbqYnLD - screens with portals inspector
https://streamable.com/b14hk - video how it works
teleportation script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Teleportation : MonoBehaviour {
[SerializeField] private GameObject otherPortal;
[SerializeField] private GameObject player;
void OnTriggerEnter(Collider col) {
if(col.tag == "Player") {
col.transform.position = new Vector3(otherPortal.transform.position.x+1, otherPortal.transform.position.y+1, otherPortal.transform.position.z+1);
Debug.Log("wszedłem w portal");
}
}
void Update() {
}
}
some informations how it is coded right now:
portals are currently in game behind 'the box', i didnt instantiate them anywhere; just changing position on lpm (blue portal) and ppm (orange portal)
portals are sticking to the walls, just like in the original game
portals have a camera attached to it and right now the cameras are static. (offtop: i have a script to move them exactly when player is moving and it quite works but also have some problems, like camera can get too far away from portal and start rendering only that green outer side of the box, and i also dont know how to fix it, so currently i didnt use this script)
the player movement im using is that from unity standard assets (if it somehow matters)
the player have a rigidbody but the portals dont; not sure if i should attach this component to them
teleportation script is attached to the both of portals - the 'otherPortal' variable is moved from inspector, like in orange portal the 'otherPortal' variable is blue portal and the other way
What you did is correct (setting the player rotation to the portal.
You can do it in onTriggerEnter after setting the position, then it should look like
player.transform.rotation = otherPortal.transform.rotation
If you do that, the player will have the same rotation. You already have something that make the camera follow the player, so it is likely that you don't need to set the camera rotation. I don't know how you did your camera follow, so I can't be sure, though. If the camera has not the proper orientation, doing Camera.main.transform.rotation = otherPortal.transform.rotation will do it.
The remaining thing that might be wring, could be that your player (and camera) is not facing the right axis. On your video, I can see that the portal faces the x-axis (the red axis in Unity editor). Check that when going forward, your player has the red axis looking forward.
It is likely that your player has the z-axis (blue) facing forward, which is (by convention) more correct and fits the names Unity uses (z-axis is also called forward-axis)
I would recomand to create the portal object (and all other objects, including the player) so that the forward-axis is the blue one. It might require editing the objects. Anycase, check that the player forward axis is that same as the portal, otherwise setting the rotation won't work

Unity - Help needed with spherical gravity?

I am working on a game which has strong base on spherical gravity. But somehow my code is not working as expected. So please have a look at my code and tell me how can I make my spherical gravity work.
public class CircularGravity : MonoBehaviour {
private Rigidbody2D rigid;
[SerializeField]
Transform planet;
[SerializeField]
float acceleration = 0.81f;
// Use this for initialization
void Start () {
rigid = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
rigid.AddForce((planet.position - transform.position).normalized * acceleration);
transform.rotation = Quaternion.LookRotation(planet.position - transform.position, transform.up);
}
}
Problem elaboration. Project is 2d. it contains a circle sprite as a planet with a collider and hexagon has a player(just a prototype) with collider and rigidbody. This script is attached to the player(hexagon). According to my logic rigidbody should apply a force to the player and push it towards the planet and it should face the planet. So even if the player is on the downward side of circle it shouldnot fall instead it shall be pushed toward the planet. But all the colliders are being neglected and player is just going to strange position
First things I would check...
Make sure the origin of your sprite is actually in the center of the image. If it's in the corner the player will be pulled toward the corner.
Make sure both the planet and player have rigid bodies and colliders. Click on the collider and make sure the edge lines up with you shapes.
Make sure both the planet and the player have their z set to zero. Lock z in both rigidbodies.

camera follows object when it rotates

I am trying to make a game where the camera follows the user, as they move around. I made the camera a child of the player and in the editor, the camera rotates around the player fine. When I play the game (in Unity) and rotate the player, the camera literally rotates instead of rotating around the player to keep the same regular following distance.
I use transform.Rotate() to rotate the player by the way.
In Summary:
Looking for camera that follows player in 3D game, that does not look different when the player turns.
issue is that the camera appears in the editor to rotate around the player perfectly, but not when transform.Rotate() is called on it during runtime in Unity.
All help is appreciated, tyvm for help.
I made the camera a child of the player and in the editor
Everything went down by doing this. You don't make the camera a child if you want it to follow the player.
What you do is to get the distance between the camera and the player in the Start() function. This is also called offset. In the LateUpdate() function, continuously move the camera to the Player's position, then add that offset to the camera's position. It is as simple as that.
public class CameraMover: MonoBehaviour
{
public Transform playerTransform;
public Transform mainCameraTransform = null;
private Vector3 cameraOffset = Vector3.zero;
void Start()
{
mainCameraTransform = Camera.main.transform;
//Get camera-player Transform Offset that will be used to move the camera
cameraOffset = mainCameraTransform.position - playerTransform.position;
}
void LateUpdate()
{
//Move the camera to the position of the playerTransform with the offset that was saved in the begining
mainCameraTransform.position = playerTransform.position + cameraOffset;
}
}

My camera rotates with my ball when i have ball as a parent gameobject of camera. what should i do?

I'm using my camera as a child gameobject of my ball, so when I move my ball camera comes with him. But the problem is I'm using rigidbody.addForce(), so when ball rotates the camera rotates with it, too.
So what should I do not to rotate my camera but only move it with my ball?
void FixedUpdate()
{
rigidbody.addForce(Input.getAxis("Horizontal"), 0, Input.getAxis("vertical"));
}
There are several ways to solve this, I'll list a few.
The first, if you don't care if your ball rotates or not, you can just disable the rotation on the ball. If you open the Constraints section in the rigidbody component, you can freeze the rotation so that the ball won't rotate.
Alternatively, you can write a script that keeps the camera always oriented a certain way. Depending on if you want the camera to rotate around the ball on any plane depends on the way you would implement this.
The third option, which is cleanest, is to not have the camera be a child of the ball. A minimal component to do this would look like this:
public class TargetFollow : MonoBehaviour
{
public Transform Target;
public float DistanceFromTarget;
void Update()
{
transform.position = Target.position + new Vector3(0, 0, DistanceFromTarget);
transform.LookAt(Target);
}
}
Just drag your ball into the 'Target' slot in your component. Keep in mind, this is super bare bones. You may want to add more variables to better control the direction the camera should be from the ball, or perhaps something that grabs a snapshot of the direction and distance the camera is from the ball in the Start method.

Categories

Resources