左手持弓,右手拉弓射箭
using UnityEngine;
using Pvr_UnitySDKAPI;
public class ArcheryController : MonoBehaviour
{
public GameObject arrowPrefab;
public Transform leftHand;
public Transform rightHand;
public float maxShootDistance = 0.5f;
public float maxShootForce = 50f;
private float currentShootForce = 0f;
private bool isCharging = false;
private Vector3 initialHandPosition;
void Update()
{
CheckChargingInput(leftHand, Pvr_ControllerManager.GetControllerState(0));
CheckChargingInput(rightHand, Pvr_ControllerManager.GetControllerState(1));
if (isCharging)
{
ChargeBow();
}
if (isCharging && (Pvr_ControllerManager.GetControllerState(0).GetButtonUp(Pvr_KeyCode.TRIGGER) ||
Pvr_ControllerManager.GetControllerState(1).GetButtonUp(Pvr_KeyCode.TRIGGER)))
{
ShootArrow();
}
}
void CheckChargingInput(Transform hand, Pvr_ControllerState controllerState)
{
// 检测射箭按钮状态
if (controllerState.GetButton(Pvr_KeyCode.TRIGGER))
{
isCharging = true;
initialHandPosition = hand.position;
}
else
{
isCharging = false;
}
}
void ChargeBow()
{
// 计算手柄拉弓的距离
float pullDistance = Vector3.Distance(rightHand.position, initialHandPosition);
// 根据距离计算力度
currentShootForce = pullDistance / maxShootDistance * maxShootForce;
// 限制最大力度
currentShootForce = Mathf.Clamp(currentShootForce, 0f, maxShootForce);
}
void ShootArrow()
{
// 创建箭的实例
GameObject arrow = Instantiate(arrowPrefab, rightHand.position, rightHand.rotation);
// 获取箭的刚体组件
Rigidbody arrowRigidbody = arrow.GetComponent<Rigidbody>();
// 应用射击力,使用当前的力度
arrowRigidbody.AddForce(rightHand.forward * currentShootForce, ForceMode.Impulse);
// 重置力度
currentShootForce = 0f;
}
}