
我正在創建一個迷你高爾夫游戲,玩家可以點擊并拖動來擊球。目前,我有一條線可以顯示出球的方向和力量。我不太確定如何在保持正確方向的同時限制線條渲染的距離(也就是功率)。我還想將線條渲染的長度與圖片左下角的功率計 ui 同步。我在下面提供了我的代碼:
private void ProcessAim()
{
if (!isAiming || !isIdle) {
return;
}
worldPoint = CastMouseClickRay();
if (!worldPoint.HasValue) {return;}
DrawLine(worldPoint.Value);
}
private void Shoot(Vector3 worldPoint)
{
// Disabling the aiming
isAiming = false;
lineRenderer.enabled = false;
Vector3 horizontalWorldPoint = new Vector3(worldPoint.x, transform.position.y, worldPoint.z);
Vector3 direction = (horizontalWorldPoint - transform.position).normalized;
float strength = Vector3.Distance(transform.position, horizontalWorldPoint);
rb.AddForce(direction * strength * shotPower);
}
private void DrawLine(Vector3 worldPoint)
{
Vector3[] positions = { transform.position, worldPoint };
lineRenderer.SetPositions(positions);
lineRenderer.enabled = true;
}
private Vector3? CastMouseClickRay()
{
// Grabs the x and y coords and the clipPlane of the camera
Vector3 screenMousePosFar = new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.farClipPlane);
Vector3 screenMousePosNear = new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.nearClipPlane);
// Converts to in-game
Vector3 worldMousePosFar = Camera.main.ScreenToWorldPoint(screenMousePosFar);
Vector3 worldMousePosNear = Camera.main.ScreenToWorldPoint(screenMousePosNear);
Vector3 direction = (worldMousePosFar - worldMousePosNear).normalized;
// Casting a ray between the two clipPlanes of the camera at the x and y coords to see if it hit any colliders
RaycastHit hit;
if (Physics.Raycast(worldMousePosNear, worldMousePosFar - worldMousePosNear, out hit, float.PositiveInfinity))
{
return hit.point;
}
else
{
return null;
}
}
uj5u.com熱心網友回復:
你正在尋找Vector3.ClampMagnitude
你可以使用它,例如
private void DrawLine(Vector3 worldPoint)
{
// get vector from your position towards worldPoint
var delta = worldPoint - transform.position;
// clamp the distance
delta = Vector3.ClampMagnitude(delta, YOUR_DESIRED_MAX_DISTANCE);
// assign back
worldPoint = transform.position delta;
Vector3[] positions = { transform.position, worldPoint };
lineRenderer.SetPositions(positions);
lineRenderer.enabled = true;
}
順便說一句,CastMouseClickRay你應該簡單地使用Camera.ScreenPointToRay
// you should cache Camera.main!
private Camera mainCamera;
private Vector3? CastMouseClickRay()
{
// you should cache Camera.main as it is expensive!
if(!mainCamera) mainCamera = Camera.main;
// simple as that you get the mouse ray
var ray = mainCamera.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out var hit))
{
return hit.position;
}
else
{
return null;
}
}
或者,如果您真的很想按照您的評論所說的去做
// Casting a ray between the two clipPlanes of the camera at the x and y coords to see if it hit any colliders
那么你不會使用Raycast無限距離的a,而是使用aPhysics.Linecast
if (Physics.Linecast(worldMousePosNear, worldMousePosFar, out var hit))
如果有任何碰撞器與 start 和 end 之間的線相交,則回傳 true。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/448004.html
