Other
Saving old Position
Hey guys. My porblem is, that I have to spawn an Prefab-object everytime the Y Position of my Spawner changed around -1.8. But due to my Code it does not and I don not know why..
using UnityEngine; using System.Collections;
public class Spawner : MonoBehaviour {
public Vector3 oldPos;
public Vector3 Pos;
public GameObject Block;
void Start () {
Vector3 oldPos = transform.position;
Vector3 BlockPos = new Vector3 (Random.Range (1.5f, -1.5f), transform.position.y, transform.position.z);
Instantiate (Block, BlockPos, transform.rotation);
}
void Update () {
Vector3 pos = transform.position;
if (oldPos.y - 1.8f == Pos.y) { //everytime the current Position is equal to the Old Position.y - 1.8f, oldPos.y -1.8 > Pos.y did not work as well
Vector3 BlockPos = new Vector3 (Random.Range (1.5f, -1.5f), transform.position.y, transform.position.z);
Instantiate (Block, BlockPos, transform.rotation);
Pos = oldPos;
}
}
}
Answer by Vicarian · Dec 22, 2016 at 07:16 PM
@WizzardH Your variable oldPos never gets updated, so Pos and oldPos will always be equivalent, thus the decision structure on line 12 will always evaluate to false.
void Update () {
Vector3 pos = transform.position;
if (oldPos.y - 1.8f == pos.y) {
Vector3 BlockPos = new Vector3 (Random.Range (1.5f, -1.5f), transform.position.y, transform.position.z);
Instantiate (Block, BlockPos, transform.rotation);
oldPos = pos;
}
}
You may want to consider a distance calculation instead of a subtraction:
if (Vector3.Distance(oldPos, pos) >= 1.8f)
//Do stuff
Thank you for your awnser :) I realised that the Object isn´t changing it´s position because it is attached to the camera (which is moving downwards with the player), so I placed the code at the camera Update function.. void Start () { Vector3 oldPos = transform.position; thePlayer = FindObjectOfType (); lastPlayerPosition = thePlayer.transform.position; }
void Update () {
Vector3 Pos = transform.position;
distanceTo$$anonymous$$ove = thePlayer.transform.position.y - lastPlayerPosition.y;
transform.position = new Vector3 (transform.position.x, transform.position.y + distanceTo$$anonymous$$ove, transform.position.z);
lastPlayerPosition = thePlayer.transform.position;
if (Vector3.Distance (oldPos, Pos) > -1.8f) {
Spawner.setBlock ();
}
}
At my spawner I now have the function setBlock ..
public void setBlock(){
Vector3 BlockPos = new Vector3 (Random.Range (1.5f, -1.5f), transform.position.y, transform.position.z);
Instantiate (Block, BlockPos, transform.rotation);
}
The problem now is, that there are a lot of blocks generated all the time. $$anonymous$$aybe thats due to the Update function but I don´t know where else to place it.. Do you have an idea?
When you take a distance, the value obtained from the function will always be positive, so
if (Vector3.Distance (oldPos, Pos) > -1.8f)
will always evaluate true, which means that you're going to get a block spawned every frame.