Trampolin problem in Unity

1

I recently started programming at Unity so I'm pretty new to what it means. I've been trying to make a kind of "springboard" or spring in a 2D project. I tried to do with the Spring2D components but I still did not find a way to do it with this, so try the following:

What I did was create a GameObject with a 2D RigidBody and Gravity Scale = 0, and create the following script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class resorte : MonoBehaviour {

    private Vector3 posicionInicial;
    private Vector2 vectorVersorDirector;
    private bool retornarPosicion = false;
    private Rigidbody2D my_rgb2;
    public float velocidadRestitucion;


    // Use this for initialization
    void Start() {
        my_rgb2 = GetComponent<Rigidbody2D>();
        posicionInicial = gameObject.transform.position;
        vectorVersorDirector = new Vector2();
    }

    // Update is called once per frame
    void Update()
    { 
        vectorVersorDirector.x = posicionInicial.x - gameObject.transform.position.x;
        vectorVersorDirector.y = posicionInicial.y - gameObject.transform.position.y;
        vectorVersorDirector.Normalize();
        if (retornarPosicion)
        {
            my_rgb2.velocity = vectorVersorDirector * velocidadRestitucion;
        }

        if (posicionInicial.y < gameObject.transform.position.y)
        {
            my_rgb2.velocity = Vector2.zero;
            gameObject.transform.position = posicionInicial;
        }
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Ground")
            retornarPosicion = true;
    }
}

What I do is let the platform move until it meets the ground, which bears the "Ground" tag. Then, I give it speed in the direction of the initial point (which I keep at the beginning of the script) and when its position is greater than the initial position, it is corrected and returns to the initial position.

The issue is that it only works once, because then the following happens:

link

I do not know if I'm messing with the logic or if I'm ignoring some Unity behavior that's escaping me. Any help you can give me, I will thank you very much.

Greetings

    
asked by Matias Sosa 20.12.2018 в 00:55
source

1 answer

0

Instead of using the update (which in fact you should use the FixedUpdate for the physics) you use an addForce when colliding with a trampoline?

collision.gameObject.rigidbody2D.AddForce(new Vector2(0f, springForce));

And there you give the springForce that you prefer.

    
answered by 26.12.2018 в 11:52