unity3d—demo(2d人物左右移动发射子弹)
目录
人物代码示例:
子弹代码示例:
总结上面代码:
注意点:
人物代码示例:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerTiao : MonoBehaviour
{
public float moveSpeed = 10f;
private float h;
private SpriteRenderer sr;
void Start()
{
sr = this.GetComponent<SpriteRenderer>();
}
void Update()
{
h = Input.GetAxis("Horizontal");
this.transform.Translate(moveSpeed * Time.deltaTime * Vector3.right * h);
if(h < 0)
{
sr.flipX = true;
}
else if(h > 0)
{
sr.flipX = false;
}
if(Input.GetKeyDown(KeyCode.Space))
{
GameObject obj = Instantiate(Resources.Load<GameObject>("BulletObj"),this.transform.position + new Vector3(sr.flipX ? -0.3f : 0.3f,0.5f,0),Quaternion.identity);
obj.GetComponent<Bullet>().ChangeDir(sr.flipX ? Vector3.left : Vector3.right);
}
}
}
子弹代码示例:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
public float moveSpeed = 5f;
private Vector3 nowDir;
void Start()
{
Destroy(this.gameObject, 3f);
}
public void ChangeDir(Vector3 dir)
{
nowDir = dir;
}
void Update()
{
this.transform.Translate(moveSpeed * Time.deltaTime * nowDir);
}
}
总结上面代码:
this.transform.Translate(moveSpeed * Time.deltaTime * nowDir); transform是属性 获取Transform组件 Translate是Transfor组件方法函数
预设体 是 GameObject 类型