我正在做一个小型游戏,将物体放在船上,然后按键使船“航行”。
要移动站立在船上的所有对象,我将每个对象的父对象设置为船中的空引导对象,然后更改船的位置。 (我也尝试过将对象育成船对象本身)
以下是应用于船对象的脚本。
在BoatScript类中设置的变量:
print(a <- add_str("b"))
启动和更新方法:
public class BoatScript : MonoBehaviour {
public List<string> boatList;
public KeyCode interact;
public GameObject tempObject;
public string whichSide;
public string direction;
public bool canSail;
}
这是我的OnTrigger方法:
void Start () {
canSail = false;
whichSide = "start";
direction = "toFinish";
speed = 0f;
}
void Update () {
if (canSail == true)
{
SetSail();
}
if (boatList.Contains("FARMER") && whichSide == "start" && Input.GetKeyDown(interact))
{
speed = 0.5f;
CharacterCheck();
}
else if (boatList.Contains("FARMER") && whichSide == "finish" && Input.GetKeyDown(interact))
{
speed = -0.05f;
CharacterCheck();
}
}
启航:
void OnTriggerEnter(Collider other)
{
Debug.Log(other.gameObject.name + " collided with " + gameObject.name);
promptText.text = "";
if(CheckValidObject(other.gameObject.name) == true) {
boatList.Add(other.gameObject.name);
logBox.text = logBox.text + "\nThe " + other.gameObject.name + " is in the boat";
}
if (other.gameObject.name == "FARMER")
{
promptText2.text = "Press E to set sail";
}
}
void OnTriggerExit(Collider other)
{
boatList.Remove(other.gameObject.name);
logBox.text = logBox.text + "\nThe " + other.gameObject.name + " has left the boat";
promptText.text = "";
if (other.gameObject.name == "FARMER")
{
promptText2.text = "";
}
}
问题:一旦船到达并撞到对撞机的另一侧,船将按预期停止,但刚从父级移除的对象开始像这样连续放大:
例如1 https://i.gyazo.com/d35ae729757b8e71c25fd1b4a3857dae.mp4
例如2 https://i.gyazo.com/80637919bfd114a42d187300b7faef25.mp4
我不太确定是什么原因造成的。非常感谢您的帮助。
答案 0 :(得分:1)
使用transform.parent
代替通过transform.SetParent(targetTransform, false);
设置父对象。第二个参数bool确定游戏对象的变换是否将保持其位置,方向和比例。通过将其设置为false,变换将保留其当前值,而将其设置为true将修改位置,方向和比例以维持世界位置。您可以检查此以获取更多信息transform.SetParent
答案 1 :(得分:0)
您确定它正在按比例放大并且没有在Z轴上向上移动吗?从我看来,它正朝着相机方向发展,但并没有扩大规模。您应该在update方法中调试位置和比例,以查看实际发生的情况。
在下面的评论中:“那么,您将不得不对其进行更仔细的调试,我首先尝试,将canSail设置为false,直到它到达末尾。也许总是执行的addParent方法是错误的,对象itemGuide可以编辑吗?编辑:我刚刚看了第二个视频,从我的角度看,它似乎很引人注目,您对放大问题的意思是因为它从船上移了出来?”
解决方案:
void SetSail()
{
promptText.text = "";
promptText2.text = "";
addParents();
if (whichSide == "sailing" && direction == "toFinish")
{
speed = 0.05f;
gameObject.transform.Translate(speed, 0, 0);
}
else if (whichSide == "sailing" && direction == "toStart")
{
speed = -0.05f;
gameObject.transform.Translate(speed, 0, 0);
}
else if (whichSide == "start" || whichSide == "finish")
{
gameObject.transform.Translate(speed, 0, 0);
canSail = false; //Adding this line solves the issues, must have been affecting transform properties to child objects.
removeParents();
}
}