我有兩個力場I &二(圖片在這裏 - https://i.stack.imgur.com/yXAhQ.png)。他們都有一個帶有bool'repel'的附加腳本,該腳本在MouseDown()上切換。這些力場需要直接吸引或擊退太空船。船舶的實際移動是通過從船上向下進行光線投射&完成的。這些光線廣播檢查力場的「排斥」布爾,然後船舶移動或朝向力場移動。所有的遊戲對象都是運動的。來回移動使用Rigidbody2D movePosition
我需要能夠通過切換他們的'repel'布爾來在力場之間來回移動船。這可以通過使用transform.Translate移動船來很好地工作。然而,碰撞是越野車,所以我決定改用Rigidbody2D.MovePosition。
現在,船可以移向ForceField I,當它檢測到ForceField II時,它會沿着一條垂直線改變其走向,這正是我想要的。但是,當它沿着X軸射線檢測到它時,它不能再移向或離開ForceField I。所以,這艘船現在只能上下移動。我如何讓船在力場之間移動?
這裏是附在船舶代碼 -
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class shipRays_test : MonoBehaviour {
public float rayDistance = 100;
public Vector2 Xspeed;
public Vector2 Yspeed;
private polarityScript polarityright;
private polarityScript polaritydown;
private Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
Debug.DrawRay (transform.position, Vector2.right * rayDistance, Color.red);
RaycastHit2D rightHit = Physics2D.Raycast (transform.position, Vector2.right, rayDistance);
Debug.DrawRay (transform.position, Vector2.down * rayDistance, Color.green);
RaycastHit2D downHit = Physics2D.Raycast (transform.position, Vector2.down, rayDistance);
if (rightHit.collider != null)
{
if (rightHit.collider.CompareTag ("forceField"))
{
polarityright = rightHit.collider.gameObject.GetComponent<polarityScript >();
if (polarityright.repel)
{
rb.MovePosition (rb.position - Xspeed * Time.fixedDeltaTime);
}
else if (!polarityright.repel)
{
rb.MovePosition (rb.position + Xspeed * Time.fixedDeltaTime);
}
}
}
if (downHit.collider != null)
{
if (downHit.collider.CompareTag ("forceField"))
{
polaritydown= downHit.collider.gameObject.GetComponent<polarityScript >();
if (polaritydown.repel)
{
rb.MovePosition (rb.position + Yspeed * Time.fixedDeltaTime);
}
else if (!polaritydown.repel)
{
rb.MovePosition (rb.position - Yspeed * Time.fixedDeltaTime);
}
}
}
}
}
您可能必須要總結你想使用和調用'rb.MovePosition()'只有一次的偏移量。在我看來,功能所做的就是存儲它給定的值並從當前位置插入,因此第二次調用它會覆蓋該值。 – Draco18s
你能告訴我一個示例代碼行嗎?我不知道應該如何繼續。我應該將對象的rb.position存儲在fixedUpdate中的變量中,並將其傳遞給rb.MovePosition? –
在兩個if語句之前:'Vector3 newPos = rb.position;'...在第一個if區塊內:'newPos + = Yspeed;'...在第二個區域內:'newPos + = Xspeed;'...之後:'rb.MovePosition(newPos)' – Draco18s