i want let camera move follow the character by smooth time.
but it is shaking when used Mathf.SmoothDamp.
here is the code.
player:
using UnityEngine;
using System.Collections;
public class playerControl2D : MonoBehaviour
{
public bool faceRight = true;
public float moveForce = 15;
public float maxSpeed = 1f;
private bool grounded = false;
private Transform groundCheck;
void Awake()
{
groundCheck = transform.Find("groundCheck");
}
void Start ()
{
// set animation speed
animation["idle"].speed = 0.5f;
animation["walk"].speed = 1.2f;
}
void Update ()
{
// check whether grounded
grounded = Physics2D.Linecast( transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));
}
void FixedUpdate ()
{
float h = Input.GetAxis("Horizontal");
// move
if( h* rigidbody2D.velocity.x < maxSpeed )
{
rigidbody2D.AddForce(Vector2.right * h * moveForce);
animation.CrossFade("walk");
}
// to run by maxSpeed
if( Mathf.Abs(rigidbody2D.velocity.x) > maxSpeed)
{
rigidbody2D.velocity = new Vector2(Mathf.Sign(rigidbody2D.velocity.x) * maxSpeed, rigidbody2D.velocity.y);
animation.CrossFade("walk");
}
// stand
if( rigidbody2D.velocity.x == 0 )
{
animation.CrossFade("idle");
}
// face to right
if( h > 0 && !faceRight )
{
Filp();
}
// face to left
if( h < 0 && faceRight )
{
Filp();
}
}
// turn the face
void Filp ()
{
faceRight = !faceRight;
Vector3 theScale = transform.localScale;
theScale.z *= -1;
transform.localScale = theScale;
}
}
camera:
using UnityEngine;
using System.Collections;
public class cameraSmooth : MonoBehaviour {
public Transform cameraTarget;
public float smoothTime = 0.1f;
private Vector2 velocity;
void Update ()
{
Vector3 newPos = transform.position;
newPos.x = Mathf.SmoothDamp( transform.position.x, cameraTarget.position.x, ref velocity.x, smoothTime );
transform.position = newPos;
}
}
}
i changed Update() to FixedUpdate()in the camera Script and it does worked!
– lyp1229