My script here is supposed to make an object bounce when it touches a touchpad, but I did not want to use rigidbody, so I used this instead. But when running the script, instead of bouncing it teleports. This is the script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bounce : MonoBehaviour
{
//adjust this to change speed
[SerializeField]
float speed = 5f;
//adjust this to change how high it goes
[SerializeField]
float height = 0.5f;
Vector3 pos;
private void Start()
{
pos = transform.position;
}
void OnTriggerEnter(Collider collision)
{
if (collision.gameObject.tag == "jumpPad")
{
//calculate what the new Y position will be
float newY = Mathf.Sin(Time.time * speed) * height + pos.y;
//set the object's Y to the new calculated Y
transform.position = new Vector3(transform.position.x, newY, transform.position.z);
}
}
}
sin should only start at 0 if your time variable starts at 0 at the start of a jump, which Time.time isn’t going to do. You want a variable which is reset to start at 0 every on every collision. Pretty sure you probably also want to put all the code from the if statement into an independent function and trigger a state change that initiates the jump and cause the function to be called as long as its occuring because I dont think your position change will be called enough(if more than once, at the “moment” of collision) to simulate an arc. You can handle the state and timekeeping with the same variable if you set it to -1 to represent false.
Also you might wanna know when the arc ends now that you have a jumpState so you can reset it. I gave an example of a simple conditional but you probably want something more complex since I assume the jump is supposed to end early if theres an obstacle and you may need to clean up the position once the condition is reached since getting the exact value of the sin wave for the end of the jump may not be reliably doable.
Lastly im guessing you wanted an arc like the first half of a sine wave, which means you want to add the value the sin wave returns to the initial position not the current position so that as the values approach 0 you return to your initial y position(unless you meant to use the negative half of the wave period as well)
so something like
if(jumpPad){
jumpState = 0;
initialY = transform.position.y
}
void Update(){
if (jumpState>-1){
calcJump(jumpState)
jumpState ++;
}
calcJump(float jumpState){
if(jumpState>0 and Sin(jumpState * Speed)<= 0){
jumpState ==-1;
}
else {
float newY = Mathf.Sin(jumpState * speed) * height + initialY;
transform.position = new Vector3(transform.position.x, newY, transform.position.z);
}