- Home /
2D camera follow lock Y-Axis
Hi.I am trying this script.With below script camera follows character all fine...But I want y-axis following to be locked so that i can make platformer game like mario. Please help.
using UnityEngine; using System.Collections;
public class SmoothFollow : MonoBehaviour { public Transform target; public float smoothDampTime = 0.2f; [HideInInspector] public new Transform transform; public Vector3 cameraOffset; public bool useFixedUpdate = false;
private CharacterControl _playerController;
private Vector3 _smoothDampVelocity;
void Awake()
{
transform = gameObject.transform;
_playerController = target.GetComponent<CharacterControl>();
}
void LateUpdate()
{
if( !useFixedUpdate )
updateCameraPosition();
}
void FixedUpdate()
{
if( useFixedUpdate )
updateCameraPosition();
}
void updateCameraPosition()
{
if( _playerController == null )
{
transform.position = Vector3.SmoothDamp( transform.position, target.position - cameraOffset, ref _smoothDampVelocity, smoothDampTime );
return;
}
if( _playerController.velocity.x > 0 )
{
transform.position = Vector3.SmoothDamp( transform.position, target.position - cameraOffset, ref _smoothDampVelocity, smoothDampTime );
}
else
{
var leftOffset = cameraOffset;
leftOffset.x *= -1;
transform.position = Vector3.SmoothDamp( transform.position, target.position - leftOffset, ref _smoothDampVelocity, smoothDampTime );
}
}
}
Answer by sysameca · Feb 10, 2015 at 09:51 AM
Just store the initial camera Y position and assign it later to the movement vector;
private float startingY;
private void Start()
{
startingY = transform.position.y;
}
private void Update()
{
Vector3 position = Vector3.SmoothDamp( transform.position, target.position - leftOffset, ref _smoothDampVelocity, smoothDampTime );
position.y = startingY;
transform.position = position;
}
Your answer

Follow this Question
Related Questions
Making a 2D platformer not go backwards. 1 Answer
[Closed] SmoothFollow trouble 0 Answers
2D 360 degress platformer example needed 0 Answers
The Mario Jump? 2 Answers
Should 2.5D use 3D or 2D settings ? 3 Answers