我目前正在创造一个团结的游戏,我已经做到了这样,游戏中的背景和障碍不断地重新生成了#34;"并创建一个循环。每件事情都运转良好,直到我为障碍物添加了第二个脚本,使它们垂直移动。添加脚本后,我收到错误:"无法从源类型转换为目标类型"。
这个使对象循环的脚本循环(Cs):
public class BgLooper : MonoBehaviour {
int numBGPanels = 10;
float cloudMax = 2.2f;
float cloudMin = -0.2f;
void Start() {
GameObject[] clouds = GameObject.FindGameObjectsWithTag ("Cloud");
foreach (GameObject cloud in clouds) {
Vector3 pos = cloud.transform.position;
pos.y = Random.Range(cloudMin, cloudMax);
cloud.transform.position = pos;
}
}
void OnTriggerEnter2D(Collider2D collider) {
Debug.Log ("Triggered: " + collider.name);
float widthOfBGobject = ((BoxCollider2D)collider).size.x;
Vector3 pos = collider.transform.position;
pos.x += widthOfBGobject * numBGPanels;
if (collider.tag == "Cloud") {
pos.y = Random.Range(cloudMin, cloudMax);
}
collider.transform.position = pos;
}
}
这是使obsticales移动的脚本(Js):
var maxX = 6.1;
var minX = -6.1;
var maxY = 4.2;
var minY = -4.2;
var moveSpeed = 0.3;
private var tChange: float = 0; // force new direction in the first Update
private var randomX: float;
private var randomY: float;
function Update () {
// change to random direction at random intervals
if (Time.time >= tChange){
randomX = Random.Range(-2.0,2.0); // with float parameters, a random float
randomY = Random.Range(-2.0,2.0); // between -2.0 and 2.0 is returned
// set a random interval between 0.5 and 1.5
tChange = Time.time + Random.Range(0.5,1.5);
}
transform.Translate(Vector3(randomX,randomY,0) * (moveSpeed / 15) * Time.deltaTime);
// if object reached any border, revert the appropriate direction
if (transform.position.x >= maxX || transform.position.x <= minX) {
randomX = -randomX;
}
if (transform.position.y >= maxY || transform.position.y <= minY) {
randomY = -randomY;
}
// make sure the position is inside the borders
transform.position.x = Mathf.Clamp(transform.position.x, minX, maxX);
transform.position.y = Mathf.Clamp(transform.position.y, minY, maxY);
}
答案 0 :(得分:0)
您应该能够访问bounds上的Collider2D属性,而不是像这样使用强制转换。
void OnTriggerEnter2D(Collider2D collider) {
Debug.Log ("Triggered: " + collider.name);
//change this line
float widthOfBGobject = collider.bounds.size.x;
Vector3 pos = collider.transform.position;
pos.x += widthOfBGobject * numBGPanels;
if (collider.tag == "Cloud") {
pos.y = Random.Range(cloudMin, cloudMax);
}
collider.transform.position = pos;
}
这应该是您的OnTriggerEnter2D
应该与更改相似的内容。