Ok, so I’ve been trying to create this mechanic where:
When the character braces itself, they will teleport themself a set distance and come out of the ground with the same speed they went in (the y velocity gets flipped then of course, so they jump up from the ground instead of just launching into the ground)
And I’m having trouble with adding the velocity back up after the teleport. Here’s the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LandingScript : MonoBehaviour {
private Rigidbody2D rb2d;
private Vector2 velocityLS;
public bool triggerZone = false;
public bool bracing = false;
public float xAddPosition = 2;
public float yAddPosition = 1;
// Use this for initialization
void Start ()
{
rb2d = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update ()
{
if (triggerZone == true)
{
if (Input.GetAxis("Vertical") < 0)
{
bracing = true;
}
else if (Input.GetButton("Vertical"))
{
bracing = false;
}
if (bracing == true && triggerZone == true)
{
float xSpeed = rb2d.velocity.x;
float ySpeed = rb2d.velocity.y;
transform.position = new Vector2(transform.position.x + xAddPosition, transform.position.y + yAddPosition);
rb2d.AddForce(new Vector2(xSpeed, -ySpeed));
bracing = false;
}
}
if (Input.GetButton("Vertical"))
{
triggerZone = false;
}
}
void OnTriggerEnter2D (Collider2D coll)
{
if (coll.gameObject.tag == "Trigger")
{
triggerZone = true;
}
}
}
Tips are welcome on basically anything really (I’m just starting out with programming…)