Isometric Unity 3D游戏.如何发射炮弹



我正在制作一个等距3D游戏。我做了两个操纵杆,一个用来移动玩家,另一个用来在释放操纵杆时发射炮弹。为了达到这个结果,我做了三次尝试,但每次都有问题。第一次尝试是这样的:

clone.velocity = transform.TransformDirection(newpos);

但这需要一个刚体,而射弹不能是刚体,因为它是从玩家内部开始的。第二次尝试是这样的:

clone.transform.Translate(dir * (launchForce));

但它没有"速度",所以它只是立即移动到这个位置,而不是移动,而是平移第三次尝试也是如此:

clone.transform.position=Vector3.MoveTowards(Player.transform.position,newpos,10f);

这是迄今为止最好的解决方案,因为它让我有可能在起始位置和新位置之间选择一个最大范围。这是完整的代码:

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
public class shoot : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler
{
private Image bgImg;
private Image joystickImg;
private Vector3 inputVector;
public GameObject proiettile;
private Vector3 dir = Vector3.zero;
private Vector3 newpos;
public float launchForce;
public Rigidbody Player;
private GameObject clone;
private void Start()
{
bgImg = GetComponent<Image>();
joystickImg = transform.GetChild(0).GetComponent<Image>();
}
public virtual void OnDrag(PointerEventData ped)
{
Vector2 pos;
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(bgImg.rectTransform, ped.position, ped.pressEventCamera, out pos))
{
pos.x = (pos.x / bgImg.rectTransform.sizeDelta.x);
pos.y = (pos.y / bgImg.rectTransform.sizeDelta.y);
inputVector = new Vector3(pos.x * 2 +1, 0, pos.y * 2 - 1);
inputVector = (inputVector.magnitude > 1.0f) ? inputVector.normalized : inputVector;
// Move joystickImg
joystickImg.rectTransform.anchoredPosition =
new Vector3(inputVector.x * bgImg.rectTransform.sizeDelta.x / 3
, inputVector.z * (bgImg.rectTransform.sizeDelta.y / 3));
}
}
public virtual void OnPointerDown(PointerEventData ped)
{
OnDrag(ped);
}
public virtual void OnPointerUp(PointerEventData ped)
{
dir.x = Horizontal();
dir.z = Vertical();
newpos = dir * (launchForce);
clone = Instantiate(proiettile, Player.transform.position, Player.transform.rotation);

//third attempt
//clone.transform.position=Vector3.MoveTowards(Player.transform.position,newpos,10f);
//second attempt
//clone.transform.Translate(dir * (launchForce));
//first attempt
//clone.velocity = transform.TransformDirection(newpos);

// joystick come back to start position
inputVector = Vector3.zero;
joystickImg.rectTransform.anchoredPosition = Vector3.zero;
//temporary solution to replace the absence of a max range for projectile
clone.timeoutDestructor = 5;
}
public float Horizontal()
{
if (inputVector.x != 0)
return inputVector.x;
else
return Input.GetAxis("Horizontal");
}
public float Vertical()
{
if (inputVector.z != 0)
return inputVector.z;
else
return Input.GetAxis("Vertical");
}
}

如果我是你,我会使用刚体尝试。只需通过设置碰撞层/禁用第一秒的碰撞器/在玩家外产生抛射物来确保它不会与玩家碰撞。为什么?两个主要原因:

刚体将为您开箱即用地处理插值(如果没有它,移动可能会出现故障(

刚体将处理与CCD的"帧间"碰撞,让你开箱即用(如果没有它,你的炮弹可能会穿过墙壁,甚至是目标,如果它足够快的话(

这两个功能将在之后为您节省大量时间

尝试之一:当我产生抛射物时,我会用SphereCast(或它的任何形状(检查它是否与什么东西碰撞。如果是,我将isTrigger更改为true,然后在"OnTriggerExit"中再次将isTriger更改为false。如果它在产卵时没有与任何东西发生冲突,我只需在开始时将isTrigger设置为false,就可以了。

最新更新