这里记录的是unity3d开发中用到的鸡零狗碎的代码片段。
1、键盘方向键移动对象
public class KeyboardMove : MonoBehaviour
{
private float speed = 5f;
void FixedUpdate ()
{
if (Input.GetAxis ("Horizontal") != 0 || Input.GetAxis ("Vertical") != 0) {
Vector2 movement = new Vector2 (Input.GetAxis ("Horizontal"), Input.GetAxis ("Vertical"));
transform.Translate (movement * speed * Time.deltaTime);
}
}
}
2、2d绑定对象的大小
gameObject.GetComponent<SpriteRenderer>().sprite.bounds.size.x;
gameObject.GetComponent<SpriteRenderer>().sprite.bounds.size.y;
3、从屏幕下方消失的时候,销毁对象
public class DestroyInvisible : MonoBehaviour {
void OnBecameInvisible ()
{
if (Camera.main != null) {
if (transform.position.y < Camera.main.ScreenToWorldPoint (new Vector3 (0f, 0f, 0f)).y) {
Destroy (gameObject);
}
} else {
Debug.Log("Camera.main is null.");
}
}
}
4、2D滚动视差背景
从老外那抄的,原理我说不清楚,这个是纵轴,也就是Y轴滚动
using UnityEngine;
using System.Collections;
public class parallaxY : MonoBehaviour {
public Transform[] backgrounds;
private float[] parallaxScales;
public float smoothing = 1f;
private Transform cam;
private Vector3 previousCamPos;
void Awake ()
{
cam = Camera.main.transform;
}
void Start ()
{
previousCamPos = cam.position;
parallaxScales = new float[backgrounds.Length];
for (int i=0; i<backgrounds.Length; i++) {
parallaxScales [i] = backgrounds [i].position.z * -1;
}
}
void Update ()
{
for (int i=0; i<backgrounds.Length; i++) {
float parallax=(previousCamPos.y -cam.position.y)*parallaxScales[i];
float backgroundTargetPosY=backgrounds[i].position.y+parallax;
Vector3 backgroundTargetPos = new Vector3(backgrounds[i].position.x,backgroundTargetPosY,backgrounds[i].position.z);
backgrounds[i].position=Vector3.Lerp(backgrounds[i].position,backgroundTargetPos,smoothing*Time.deltaTime);
}
previousCamPos = cam.position;
}
}
背景作为数组,对象的position.Z影响移动速度