- Home /
problem with moving platform
i have problem with circle moving platform
i have Circle, the circle rotate around itself and move right and left
when player jump on the circle, the player be child of the Circle
it works fine, but sometime doesn’t (not be a child of a circle)
Circle attached with PlatformController
Player attached with PlayerController
PlatformController.cs
public class PlatformController : MonoBehaviour {
public int rotateSpeed;
public int moveSpeed;
public bool isMoving;
void Start () {
rotateSpeed = Random.Range (1,7);
moveSpeed = Random.Range (1,7);
}
void FixedUpdate () {
transform.Rotate (0,0,1);
if (isMoving) {
transform.Translate (moveSpeed * Time.deltaTime ,0,0 , Space.World);
}
}
void OnTriggerEnter2D (Collider2D other) {
if (other.gameObject.tag == "rightBorder") {
moveSpeed = -moveSpeed;
}
if (other.gameObject.tag == "leftBorder") {
moveSpeed = Mathf.Abs (moveSpeed);
}
}
}
Player Controller Script
public class PlayerController : MonoBehaviour {
Rigidbody2D rb;
public float jumpSpeed;
public bool touchGround;
// Use this for initialization
void Start () {
rb = GetComponent();
}
// Update is called once per frame
void Update () {
Jump ();
}
public void Jump () {
if (Input.GetKeyDown (KeyCode.Space)) {
if (touchGround) {
rb.constraints = RigidbodyConstraints2D.None;
rb.velocity = new Vector2 (0, jumpSpeed);
}
}
}
void OnCollisionEnter2D (Collision2D other) {
if (other.gameObject.tag == "ground") {
touchGround = true;
this.transform.parent = other.gameObject.transform;
rb.constraints = RigidbodyConstraints2D.FreezePositionY;
}
}
void OnCollisionExit2D (Collision2D other) {
if (other.gameObject.tag == "ground") {
touchGround = false;
this.transform.parent = null;
rb.constraints = RigidbodyConstraints2D.None;
}
}
}
i need to know why sometime the player in the game can’t be child of the circle ?
Thanks , sorry for my english
Answer by madks13 · Jul 23, 2018 at 10:39 AM
If you placed the jump inside the Update, keep in mind that you can have 200+ updates per second, depending on the scene complexity, your computer's power and some other factors.
You try to detect a keyboard key being pressed, but at the rate of update, if i recall correctly, it will detect it several times before the key is let up, and setting/unsetting the parent at that rate might seems it look like sometimes it is not working, but you just stopped on the part when it was unset.
It's enough for Unity to catch the jump key 2 times in a row and you will unset the parent before the player character left the ground. Velocity doesn't teleport the player object outside the reach of ground, but accelerates it in a direction, which might not be instant (depends on the colliders position and size and how you detect ground). In any case, add a few Debug.Log inside methods to see if they don't activate too much.
Other than that, i don't see anything else as possible problem, based on your description.