Question by
iEpic · Oct 31, 2016 at 09:47 PM ·
2d game2d-platformer2d-gameplaycamera follow2d camera
How Do I Lock The Y Axis In A Camera Follow Script?
I don't want the camera to follow the player when he jumps.
I'm a beginner and have no idea how to do this. Here is my script...
using System;
using UnityEngine;
namespace UnityStandardAssets._2D
{
public class Camera2DFollow : MonoBehaviour
{
public Transform target;
public float damping = 1;
public float lookAheadFactor = 3;
public float lookAheadReturnSpeed = 0.5f;
public float lookAheadMoveThreshold = 0.1f;
private float m_OffsetZ;
private Vector3 m_LastTargetPosition;
private Vector3 m_CurrentVelocity;
private Vector3 m_LookAheadPos;
// Use this for initialization
private void Start()
{
m_LastTargetPosition = target.position;
m_OffsetZ = (transform.position - target.position).z;
transform.parent = null;
}
// Update is called once per frame
private void Update()
{
// only update lookahead pos if accelerating or changed direction
float xMoveDelta = (target.position - m_LastTargetPosition).x;
bool updateLookAheadTarget = Mathf.Abs(xMoveDelta) > lookAheadMoveThreshold;
if (updateLookAheadTarget)
{
m_LookAheadPos = lookAheadFactor*Vector3.right*Mathf.Sign(xMoveDelta);
}
else
{
m_LookAheadPos = Vector3.MoveTowards(m_LookAheadPos, Vector3.zero, Time.deltaTime*lookAheadReturnSpeed);
}
Vector3 aheadTargetPos = target.position + m_LookAheadPos + Vector3.forward*m_OffsetZ;
Vector3 newPos = Vector3.SmoothDamp(transform.position, aheadTargetPos, ref m_CurrentVelocity, damping);
transform.position = newPos;
m_LastTargetPosition = target.position;
}
}
}
Comment
Answer by ElijahShadbolt · Nov 01, 2016 at 12:55 AM
Above the Start function, add this line
private float initialY;
Then in the Start function add this line
initialY = transform.position.y;
Then just before transform.position = newPos;
add this line
newPos.y = initialY;
Your answer
Follow this Question
Related Questions
2d game kit ellen (player) getting glitched on collider 0 Answers
Ragdoll Movement Script, Help! 0 Answers
How to make a functioning lantern in 2D 0 Answers
How Do I stop AI Following player on the Y-axis? 0 Answers
How do you Isolate Physics2D.OverlapArea to a single script/gameObject/Instance? 0 Answers