Hi everyone I'm doing a cannonball mode where players will have a UI panel that looks like a snipe screen. This camera will follow the enemy while in regular play there is another camera for normal play mode( this one stays in place). However when I switch between the two wherever the cannon camera moves when I exit with "E" it stays in that moved position. Is there any way where I can manually revert the position of the camera back in place?
public class CameraFollow : MonoBehaviour
{
public Transform target;
public float smoothSpeed = 0.125f;
public Vector3 offset;
public GameObject scopeOverlay;
public GameObject Camera;
void FixedUpdate ()
{
if (Input.GetKeyDown ("d"))
{
Camera.SetActive (false);
scopeOverlay.SetActive(true);
Vector3 desiredPosition = target.position + offset;
Vector3 smoothedPosition = Vector3.Lerp (transform.position, desiredPosition, smoothSpeed);
transform.position = smoothedPosition;
transform.LookAt (target);
}
if (Input.GetKeyDown ("e"))
{
Camera.SetActive (true);
scopeOverlay.SetActive(false); //To disable it
}
}
}
Save the initial transform values and restore them like so;
private Vector3 initialPosition;
private Quaternion initialRotation;
private void Start ()
{
// Save initial transform values
initialPosition = transform.position;
initialRotation = transform.rotation;
}
void FixedUpdate ()
{
if (Input.GetKeyDown("d"))
{
Camera.SetActive(false);
scopeOverlay.SetActive(true);
Vector3 desiredPosition = target.position + offset;
Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
transform.position = smoothedPosition;
transform.LookAt(target);
}
if (Input.GetKeyDown("e"))
{
// Restore transform values
transform.position = initialPosition;
transform.rotation = initialRotation;
Camera.SetActive(true);
scopeOverlay.SetActive(false); //To disable it
}
}
Related
I have a ball that move forward and bounce and rotate, and I want the camera to follow it and rotate with it so the camera always look at the ball from behind. So I made the script bellow but the camera didn't look at the ball when rotating!
NB: I didn't use camera as a child of the ball because I don't want the camera to bounce.
Camera Script:
public Transform Ball;
private Vector3 Offset;
// Use this for initialization
void Start () {
Offset = transform.position - Ball.transform.position;
}
// Update is called once per frame
void LateUpdate () {
transform.position = new Vector3(Ball.transform.position.x + Offset.x, transform.position.y, Ball.transform.position.z + Offset.z);
transform.rotation = Ball.transform.rotation;
}
[SerializeField]
private Transform target;
[SerializeField]
private Vector3 offsetPosition;
[SerializeField]
private Space offsetPositionSpace = Space.Self;
[SerializeField]
private bool lookAt = true;
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;
}
}
The target is your player gameobject
I'm struggling with this for quit some time now. I have GameObject, being a sphere, which is my player on a 3d Terrain. I have a Camera which is always on a fixed distance from the player, follows it where it goes with below script:
public GameObject player;
private Vector3 offset;
// Use this for initialization
void Start () {
offset = transform.position - player.transform.position;
}
void LateUpdate () {
transform.position = player.transform.position + offset;
}
So far so good. However what I actually want is that the camera rotates with the player, so it always looks into the direction where the sphere is moving, but always stays behind the player at the same fixed distance, so that the player is always visible in the camera view.
There are a lot of scripts available, but the problem with the onces I've seen so far is that the camera indeed rotate with the player, but because the player actually is a rolling sphere the camera view is rolling and turning as well.
The best script I found so far is below, but this one has the same problem as the other onces, the camera rolls with the player.
public Transform target;
public float distance = 3.0f;
public float height = 3.0f;
public float damping = 5.0f;
public bool smoothRotation = true;
public bool followBehind = true;
public float rotationDamping = 10.0f;
void Update () {
Vector3 wantedPosition;
if(followBehind)
wantedPosition = target.TransformPoint(0, height, -distance);
else
wantedPosition = target.TransformPoint(0, height, distance);
transform.position = Vector3.Lerp (transform.position, wantedPosition, Time.deltaTime * damping);
if (smoothRotation) {
Quaternion wantedRotation = Quaternion.LookRotation(target.position - transform.position, target.up);
//Quaternion ownRotation = Quaternion.RotateTowards;
transform.rotation = Quaternion.Slerp (transform.rotation, wantedRotation, Time.deltaTime * rotationDamping);
}
else transform.LookAt (target, target.up);
}
Can anyone help me with this please?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollow : MonoBehaviour {
public GameObject player;
public float cameraDistance = 10.0f;
// Use this for initialization
void Start () {
}
void LateUpdate ()
{
transform.position = player.transform.position - player.transform.forward * cameraDistance;
transform.LookAt (player.transform.position);
transform.position = new Vector3 (transform.position.x, transform.position.y + 5, transform.position.z);
}
}
My solution (based on #brennon-provencher answer) with smoothness and auto offset:
public class CameraFollow : MonoBehaviour
{
public GameObject target;
public float speed = 5;
Vector3 offset;
void Start()
{
offset = target.transform.position - transform.position;
}
void LateUpdate()
{
// Look
var newRotation = Quaternion.LookRotation(target.transform.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, speed * Time.deltaTime);
// Move
Vector3 newPosition = target.transform.position - target.transform.forward * offset.z - target.transform.up * offset.y;
transform.position = Vector3.Slerp(transform.position, newPosition, Time.deltaTime * speed);
}
}
You need to move your camera position based on sphere movement direction -
public GameObject player;
private Vector3 offset;
float distance;
Vector3 playerPrevPos, playerMoveDir;
// Use this for initialization
void Start () {
offset = transform.position - player.transform.position;
distance = offset.magnitude;
playerPrevPos = player.transform.position;
}
void LateUpdate () {
playerMoveDir = player.transform.position - playerPrevPos;
playerMoveDir.normalize();
transform.position = player.transform.position - playerMoveDir * distance;
transform.LookAt(player.transform.position);
playerPrevPos = player.transform.position;
}
Edit 2: To fix flickering camera, try this -
void LateUpdate () {
playerMoveDir = player.transform.position - playerPrevPos;
if (playerMoveDir != Vector3.zero)
{
playerMoveDir.normalize();
transform.position = player.transform.position - playerMoveDir * distance;
transform.position.y += 5f; // required height
transform.LookAt(player.transform.position);
playerPrevPos = player.transform.position;
}
}
I have a character(robot Kyle) and I can move the character from side to side, and forwards. When the character begins to move backwards it disappears for no reason.
Also, how would I move the character in the direction of the mouse? I have it so it faces in direction of the mouse, but the camera angle distorts that a little bit.
using UnityEngine;
using System.Collections;
public class PlayerScript : MonoBehaviour {
public GameControlScript control;
float strafeSpeed = 2;
Animator anim;
bool jumping = false;
void Start () {
anim = GetComponent<Animator>();
}
void Update () {
if (Input.GetKey(KeyCode.RightArrow)){
Vector3 newPosition = this.transform.position;
newPosition.x++;
this.transform.position = newPosition;
}
if (Input.GetKey(KeyCode.LeftArrow)){
Vector3 newPosition = this.transform.position;
newPosition.x--;
this.transform.position = newPosition;
}
if (Input.GetKey(KeyCode.UpArrow)){
Vector3 newPosition = this.transform.position;
newPosition.z++;
this.transform.position = newPosition;
}
if (Input.GetKey(KeyCode.DownArrow)){
Vector3 newPosition = this.transform.position;
newPosition.z--;
this.transform.position -= newPosition;
}
Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 1000);
Vector3 lookPos = Camera.main.ScreenToWorldPoint(mousePos);
lookPos = lookPos - this.transform.position;
float angle = Mathf.Atan2(lookPos.z, lookPos.x) * Mathf.Rad2Deg;
this.transform.rotation = Quaternion.AngleAxis(angle, Vector3.down);
}
void OnTriggerEnter(Collider other)
{
if(other.gameObject.name == "Powerup(Clone)")
{
control.PowerupCollected();
}
else if(other.gameObject.name == "Obstacle(Clone)" &&
jumping == false)
{
control.SlowWorldDown();
}
Destroy(other.gameObject);
}
}
ScreenToWorldPoint may be your problem because you are fixing 1000 as the distance between the camera and your object.
Checkout out this link and try to log your lookPos variable.
Trying to make it follow x-axis only. Only follows y when I replace with .y .y
It just doesn't want to work, no matter what I try. (Just started game dev today) I'm pretty noob at coding.
using UnityEngine;
using System.Collections;
public class FollowCamera : MonoBehaviour
{
public float interpVelocity;
public float minDistance;
public float followDistance;
public GameObject target;
public Vector3 offset;
Vector3 targetPos;
// Use this for initialization
void Start()
{
targetPos = transform.position;
}
// Update is called once per frame
void FixedUpdate()
{
if (target)
{
Vector3 posNoZ = transform.position;
posNoZ.z = target.transform.position.z;
Vector3 targetDirection = (target.transform.position - posNoZ);
interpVelocity = targetDirection.magnitude * 5f;
Vector3 factorTowardsTarget = (targetDirection.normalized * interpVelocity * Time.deltaTime);
targetPos = new Vector3(transform.position.x, transform.position.y + factorTowardsTarget.y, transform.position.z);
transform.position = Vector3.Lerp(transform.position, targetPos + offset, 0.25f);
}
}
}
I don't really know much about what I'm doing either, but I gave it a shot. This is my first post.
From what I understand there's a certain order they have to be in, X then Y then Z. And the Y is what was getting the modifier added to it. I just put the modifier on the X position instead.
I tested it, it seems to work.
I just changed this part:
targetPos = new Vector3(transform.position.x, transform.position.y + factorTowardsTarget.y, transform.position.z);
To this:
targetPos = new Vector3(transform.position.x + factorTowardsTarget.x, transform.position.y, transform.position.z);
Result:
using UnityEngine;
using System.Collections;
public class FollowCamera : MonoBehaviour
{
public float interpVelocity;
public float minDistance;
public float followDistance;
public GameObject target;
public Vector3 offset;
Vector3 targetPos;
// Use this for initialization
void Start()
{
targetPos = transform.position;
}
// Update is called once per frame
void FixedUpdate()
{
if (target)
{
Vector3 posNoZ = transform.position;
posNoZ.z = target.transform.position.z;
Vector3 targetDirection = (target.transform.position - posNoZ);
interpVelocity = targetDirection.magnitude * 5f;
Vector3 factorTowardsTarget = (targetDirection.normalized * interpVelocity * Time.deltaTime);
targetPos = new Vector3(transform.position.x + factorTowardsTarget.x, transform.position.y, transform.position.z);
transform.position = Vector3.Lerp(transform.position, targetPos + offset, 0.25f);
}
}
}
This code makes the camera follow the object only on the x position
public Camera MyCamera; // The camera you want to follow the GameObject
public GameObject ObjectToFollow; // What you want to follow
private Vector3 CameraPos; // Variable that contains the Cameras x,y,z position
void Start()
{
CameraPos = MyCamera.transform.position; // stores the Camera's position in the variable
}
// Update is called once per frame
void Update () {
CameraPos.x = ObjectToFollow.transform.position.x; // Change The X position on the camera variable to be the same as the ObjectToFollow X position
MyCamera.transform.position = CameraPos; // Moves the Camera to the new position
}
I have just started programming Unity 2d, and I have faced one large problem: How do I move the camera? The script is attached to the object "player". I want it to move with the player. Thanks!
/*
I
*/
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
public float speed = 10; //Float for speed
public string hAxis = "Horizontal";
void Start ()
{
//empty
}
void FixedUpdate ()
{
if (Input.GetAxis (hAxis) < 0) //Left
{
Vector3 newScale = transform.localScale;
newScale.y = 1.0f;
newScale.x = 1.0f;
transform.localScale = newScale;
}
else if (Input.GetAxis (hAxis) > 0) //Right
{
Vector3 newScale =transform.localScale;
newScale.x = 1.0f;
transform.localScale = newScale;
}
//Position transformation
transform.position = transform.position + transform.right * Input.GetAxis(axisName) * speed * Time.deltaTime;
}
}
Without any scripts, you could just drag the Camera GameObject to be a child of the player and the camera would start following the player position.
For a script, try this, set player as the target.
using UnityEngine;
using System.Collections;
public class SmoothCamera2D : MonoBehaviour {
public float dampTime = 0.15f;
private Vector3 velocity = Vector3.zero;
public Transform target;
// Update is called once per frame
void Update ()
{
if (target)
{
Vector3 point = camera.WorldToViewportPoint(target.position);
Vector3 delta = target.position - camera.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, point.z)); //(new Vector3(0.5, 0.5, point.z));
Vector3 destination = transform.position + delta;
transform.position = Vector3.SmoothDamp(transform.position, destination, ref velocity, dampTime);
}
}
}