先制作箭矢预制体
将Rigidbody2D改为:
Arrow.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Arrow : MonoBehaviour
{
public float speed;//速度
public int damage;//伤害
private Rigidbody2D rb2d;
//private Vector3 startPos;
// Start is called before the first frame update
void Start()
{
speed = 50f;
rb2d = GetComponent<Rigidbody2D>();
rb2d.velocity = transform.right * speed;//transform.right代表方向即x轴
//startPos = transform.position;
transform.localScale = new Vector2(-1, 1);
}
// Update is called once per frame
void Update()
{
}
private void FixedUpdate()
{
}
}
将箭矢的预制体拖入代码PlayerShoot.cs的ArrowPrefab(GameObject类型)当中,
PlayerShoot.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerShoot : MonoBehaviour
{
public Animator anim;
public GameObject arrowPrefab;
bool shootPressed;
Vector3 arrowPos = new Vector3(0.11f, -0.38f, 0f);//箭矢发射的位置
Quaternion arrowRotation = Quaternion.identity;//箭矢朝向
// Start is called before the first frame update
void Start()
{
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.J))
{
shootPressed = true;
}
}
private void FixedUpdate()
{
Shoot();
SwitchAnim();
}
void Shoot()
{
if(shootPressed == true)
{
anim.SetBool("Shooting", true);
float faceDirection = transform.localScale.x;//角色朝向
if (faceDirection > 0)//角色朝左
{
arrowRotation = Quaternion.Euler(0.0f, 180.0f, 0.0f);
Instantiate(arrowPrefab, transform.position + arrowPos, arrowRotation);
}
else//角色朝右
{
arrowRotation = Quaternion.Euler(0.0f, 0.0f, 0.0f);
Instantiate(arrowPrefab, transform.position + arrowPos, arrowRotation);
}
shootPressed = false;
}
}
void SwitchAnim()
{
}
}
效果如图:
(动作动画尚未完善)
-----------------------------------------------------------------------------------------------------