How To Return 3D Ball to Original Position After It Stops Moving/Rolling
Im new to Unity and coding in C# in general. I've been trying to make the ball I have in my game return to its original position after it stops moving. I just can't seem to make this work for whatever reason. I've experimented on my own, looked online in the forums, on YouTube, and still got nothing. Any solution will be much appreciated. Code is down below:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallControl : MonoBehaviour
{
private Vector3 originalPos;
private float speed;
public Vector3 velocity;
private new Rigidbody gameObject;
public new Vector3 transform;
void OnTriggerEnter(Collider other)
{
if (other.name == "Cup")
{
Debug.Log("COMPLETE!");
}
}
void Update()
{
speed = gameObject.velocity.magnitude;
if (speed < 0.5)
{
Reset();
}
}
void Reset()
{
gameObject.transform.position = originalPos;
}
void Start()
{
originalPos = gameObject.transform.position;
}
}
Answer by tormentoarmagedoom · Sep 10, 2018 at 07:17 AM
Good day.
First, i recommend you to put the Start method at the beggining of the script, (have no consequences for running the game, but it will help you and everybody reading your code)
Then, the code is 99.5% correct. You only forget one thing. Remeber that ALWAYS you write a number with decimals (a float number) you need to put an "f" at the end of the number, to indicate the program that is a number and not variable.variable
For next time, you should debug your code to see what is happening. Here you should see that the method Reset() is never called.
So at the Update, in the if, put the f after the 0.5:
speed = gameObject.velocity.magnitude;
if (speed < 0.5f)
{
Reset();
}
Bye!