- Home /
Proximity checker
Hi everyone,
I'm doing the Challenge: Moving sound and in the example game, there's an object that starts moving when the player gets close to it.
So my question is: How do I check when the player is close enough to trigger the action that I want?
public class RiseAndRun : MonoBehaviour
{
public Vector3 positionChange;
public Vector3 positionChangeHorizontal;
readonly double distance = 0.5;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//if (condition)
//{
if (this.transform.position.y < 1.5)
{
transform.position += (positionChange * Time.deltaTime);
}
if (this.transform.position.y >= 1.5)
{
transform.position += (positionChangeHorizontal * (Time.deltaTime * 10));
}
//}
}
}
Answer by YourShadowDani · Apr 15 at 02:52 PM
The easiest way is probably a spherecast: https://docs.unity3d.com/ScriptReference/Physics.SphereCast.html
You set it to your current position, set the size to the distance you want to detect the player, then when the spherecast detects something hit, verify its the player (checking for the players script is a good way GetComponent() ).
If it IS the player, then move in the direction you want to move at whatever distance.
Your answer
Follow this Question
Related Questions
Character is running through terrain instead of over it 0 Answers
I cant move my character,My character wont move 0 Answers
Coding Help 0 Answers
How can I have a CharacterController's height make it to where the feet are correctly on the ground? 0 Answers
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers