Hey guys, Year 1 game dev here making my first game for study. Basis of the game is to throw a ball that teleports you either after 1 second or when Space key is pressed. Right now I can’t get the player to teleport to the ball on KeyPress and I’m not sure why.
Here is my current throwing script
Rigidbody rb;
[SerializeField]
public GameObject prefab;
public int forceAmount;
public float throwSpeed;
public bool abletothrow;
public GameObject player;
// public GameObject instance;
GameObject ball;
void Start()
{
// GameObject instance = Instantiate(prefab);
// teleBall = Instantiate (obj);
// teleBall.SetActive(false);
prefab.gameObject.GetComponent<DoubleColliderToss>().player = gameObject;
}
IEnumerator WaitForThrow()
{
// suspend execution for 5 seconds
yield return new WaitForSeconds(1);
abletothrow = true;
Debug.Log("Coroutine WaitForThrow worked");
}
void Update()
{
if (abletothrow == false)
{
print("Cannot throw");
}
if (Input.GetButton("Fire1"))
{
throwSpeed += 0.1f; //lowers charge up time
if (throwSpeed >= 15)
{
throwSpeed = 15;
Debug.Log("Charging Celestial");
}
}
if (Input.GetKey(KeyCode.Space))
{
player.transform.position = gameObject.transform.position;
Debug.Log("Space input works");
}
if (abletothrow == true && (Input.GetButtonUp("Fire1")))
{
GameObject teleBall = Instantiate(prefab);
abletothrow = false;
StartCoroutine("WaitForThrow");
teleBall.transform.position = transform.position + Camera.main.transform.forward * forceAmount;
rb = teleBall.GetComponent<Rigidbody>();
rb.velocity = Camera.main.transform.forward * throwSpeed;
throwSpeed = 5;
Sorry for messy code, I am still learning. And here is my teleportation script:
{
public GameObject player;
Rigidbody rb;
// CapsuleCollider capsule;
bool tossed = false;
void Start()
{
//capsule = GetComponent<CapsuleCollider>();
}
// IEnumerator Tele()
// {
// if (Input.GetButton(KeyCode.Space))
//
// {
//
// }
// yield return new WaitForSeconds(1);
// player.transform.position = transform.position;
// Destroy(gameObject);
// // capsule.enabled = false;
// }
void OnTriggerEnter(Collider other)
{
if (other.tag == "Player") return;
if (other.tag == "BouncePlatform") return;
//checks if collider is player or platform that cannot be teleported to
tossed = true;
//capsule.enabled = true; //capsule collider thats the same size as player activates on collision to check if player can fit
// Debug.Log("Capsule is enabled");
// Time.timeScale = 0;
}
void OnCollisionStay(Collision col)
{
if (tossed)
{
tossed = false;
player.transform.position = transform.position;
Destroy(gameObject);
}
}
}