1.1 实现物体的移动
1.物体移动的目的——控制物体在场景中躲的移动,躲子弹
2.物体移动的实现方法:
(1)通过transform类中的position实现。
Vector2 trans = transform.position;
float Horizontal = Input.GetAxisRaw("Horizontal");
float Vertical = Input.GetAxisRaw("Vertical");
trans.y += highSpeed * Vertical * Time.deltaTime;
trans.x += highSpeed * Horizontal * Time.deltaTime;
transform.position = trans;
该方法实现简单,但是存在缺点,当物体与带有box collider 2D的物体碰撞时,会发生抖动。于是,便引入了通过刚体组件实现物体的移动。
(2)通过刚体组件中MovePosition()函数实现物体移动。
void Start()
{
rgd = GetComponent<Rigidbody2D>();
}
private void Move()
{
Vector2 trans = transform.position;
float Horizontal = Input.GetAxisRaw("Horizontal");
float Vertical = Input.GetAxisRaw("Vertical");
trans.y += highSpeed * Vertical * Time.deltaTime;
trans.x += highSpeed * Horizontal * Time.deltaTime;
transform.position = trans;
rgd.MovePosition(trans);
}
1.2物体移动的动画制作
1.该行为的目的——使画面更加生动
2.如何实现:
1,给物体添加动画组件animator
2,点击预制体,制作动画,具体方法:
(1)在windows中呼唤出animation窗口,添加动画
(2)将图片拖入animation窗口,由于最后一张图会直接切到第一张图,故需要将最后一张图在最后一帧复制一次;
(3)完成物体各个动作的动画制作
3,通过animator控制物体的动画显示:
(1)在Assets中创建animatorController组件,将其拖到物体animator组件中;
(2)双击打开animatorcontroller,通过blend tree 或 通过Make transition添加动画的交换条件 或 两者共同作用;
(3)通过代码修改参数控制动画的交互。
if (Mathf.Approximately(Horizontal,-1))
{
animator.SetFloat("MoveX", 0);
}
if (Mathf.Approximately(Horizontal,1))
{
animator.SetFloat("MoveX", 0.5f);
}
if (Mathf.Approximately(Horizontal,0))
{
animator.SetFloat("MoveX", 1);
}
其中Input.GetAxisRaw("Horizontal");的输出为(-1)或者(1)