- Home /
MAKE A LEVITATING PLATFORM REACT TO A PLAYER'S JUMP?
So I was creating the behavior for some 3d platform, which makes the platform levitate slowly in Y axis using Mathf.Sin to make it appear smooth. I want to find a way of making the platform react to whenever a player jumps on top of it, as if the movement of the platform suddenly goes down, but gradually starts moving up to where it was using Mathf.Sin and it keeps levitating as usual. Do you guys have any suggestions?? I was thinking of tweaking the mathf.Sin curve, but I don't know how...
Here is the code:
public class LanternMove : MonoBehaviour {
private Vector3 _startPos;
private Vector3 _prevPos;
private float _extraForce = 40f;
private bool _characterOnTop = false;
private float _lanternDistance = 0.4f;
// Use this for initialization
void Start () {
_startPos = transform.position;
}
// Update is called once per frame
void Update () {
Levitate();
}
void Levitate() {
if(!_characterOnTop)
transform.position = _startPos + new Vector3(0.0f, Mathf.Sin(Time.time) * _lanternDistance, 0.0f);
if (_characterOnTop) {
Vector3 ypos = transform.position;
ypos.y -= _extraForce * Time.deltaTime;
transform.position = ypos;
}
}
void OnCollisionEnter(Collision other) {
if (other.gameObject.tag == "Player") {
_characterOnTop = true;
_prevPos = transform.position;
}
}
}
Answer by NerdHerdGames · Jan 30, 2018 at 04:07 AM
Have you considered using RigidBody.AddForce ? Maybe add X amount of force downwards when the player jumps for float Y seconds, then add X amount up force up for Y seconds after Y seconds. Something like...
public float Y;
private float YTimer;
public float XForce;
private bool ApplyingDownwardForce;
void Update() {
if(YTimer > 0) {
YTimer -= time.deltaTime;
if(YTimer < 0 && ApplyingDownwardForce) { //start moving back up
YTimer = Y;
ApplyingDownwardForce = false;
gameObject.getComponent<RigidBody>().AddForce(new vector3(0, 2X, 0)); //2X yo compensate for -X in onCollision (not sure if this is right though...)
}
else if(YTimer < 0 && !ApplyingDownwardForce){
gameObject.getComponent<RigidBody>().AddForce(new vector3(0, -X, 0)); //stop applying force
}
}
}
void OnCollisionEnter(Collision other) {
if (other.gameObject.tag == "Player" && !AppliyingDownwardForce) {
ApplyingDowardForce = true;
gameObject.getComponent<RigidBody>().AddForce(new vector3(0, -X, 0));
YTimer = y;
_characterOnTop = true;
_prevPos = transform.position;
}
}
Your answer
Follow this Question
Related Questions
Why isn't my script to move particles working? 0 Answers
Physics platform character controller sliding issue NO parenting 0 Answers
Objects stuck dragging across floor 1 Answer
Ball hitting physics? 0 Answers