【发布时间】:2020-04-09 15:57:23
【问题描述】:
使用 (unity 2019.3.7f1) 2d。 我有一个玩家使用回撤机制四处移动并且具有最大功率(例如在愤怒的小鸟中)。 我正在尝试绘制一条线(使用线渲染器),以显示玩家将要走的确切路径。我试图让线条曲线就像玩家的路径一样。到目前为止,我只设法以非常磨损的方式制作一条直线。 已知的变量是跳跃力和球员的位置,没有摩擦。我相信重力是一个常数(-9.81)。另外,我想要一个变量来控制线条的长度。而且,如果可能的话,这条线不会穿过物体,并且会像有一个对撞机一样工作。
// 编辑
这是我当前的代码。我更改了函数,所以它会返回列表的点,因为我希望能够在 Update() 中访问它,所以它只会在我按住鼠标按钮时绘制。
我的问题是轨迹线似乎没有弯曲,它成直角但它是直的。线条以正确的方向和角度绘制,但我最初的线条不弯曲问题保持不变。如果你能请回来给我一个答案,我将不胜感激。
enter code here
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TrajectoryShower : MonoBehaviour
{
LineRenderer lr;
public int Points;
public GameObject Player;
private float collisionCheckRadius = 0.1f;
public float TimeOfSimulation;
private void Awake()
{
lr = GetComponent<LineRenderer>();
lr.startColor = Color.white;
}
// Update is called once per frame
void Update()
{
if (Input.GetButton("Fire1"))
{
lr.positionCount = SimulateArc().Count;
for (int a = 0; a < lr.positionCount;a++)
{
lr.SetPosition(a, SimulateArc()[a]);
}
}
if (Input.GetButtonUp("Fire1"))
{
lr.positionCount = 0;
}
}
private List<Vector2> SimulateArc()
{
float simulateForDuration = TimeOfSimulation;
float simulationStep = 0.1f;//Will add a point every 0.1 secs.
int steps = (int)(simulateForDuration / simulationStep);
List<Vector2> lineRendererPoints = new List<Vector2>();
Vector2 calculatedPosition;
Vector2 directionVector = Player.GetComponent<DragAndShoot>().Direction;// The direction it should go
Vector2 launchPosition = transform.position;//Position where you launch from
float launchSpeed = 5f;//The initial power applied on the player
for (int i = 0; i < steps; ++i)
{
calculatedPosition = launchPosition + (directionVector * ( launchSpeed * i * simulationStep));
//Calculate gravity
calculatedPosition.y += Physics2D.gravity.y * (i * simulationStep);
lineRendererPoints.Add(calculatedPosition);
if (CheckForCollision(calculatedPosition))//if you hit something
{
break;//stop adding positions
}
}
return lineRendererPoints;
}
private bool CheckForCollision(Vector2 position)
{
Collider2D[] hits = Physics2D.OverlapCircleAll(position, collisionCheckRadius);
if (hits.Length > 0)
{
for (int x = 0;x < hits.Length;x++)
{
if (hits[x].tag != "Player" && hits[x].tag != "Floor")
{
return true;
}
}
}
return false;
}
}
【问题讨论】:
标签: c# unity3d game-physics physics prediction