The casted ray is persisting.
i am trying to make a ball juggle and ,i am casting a ray that hits the gameobject ,after casting it a single time with the mouse button the ray keeps on persisting and the ball keeps on jumping from the position that the ray was casted before,pls help. it uses both touch and mouse input the same problem occurs for both,
here is my code:
public class triggerbounce : MonoBehaviour { RaycastHit hit; Ray ray; Ray ray2; public Rigidbody player; // Start is called before the first frame update void Start() {
}
// Update is called once per frame
void Update()
{
if (Input.touchCount > 0 )
{
ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
}
if (Physics.Raycast(ray,out hit,Mathf.Infinity))
{
if (hit.transform.gameObject.name == "playa")
{
player.AddForce((hit.collider.gameObject.transform.position - hit.point).normalized * 10, ForceMode.VelocityChange);
}
}
if (Input.GetMouseButtonUp(0)) {
ray2 = Camera.main.ScreenPointToRay(Input.mousePosition);
Debug.DrawRay(ray2.origin,ray2.direction*20,Color.red);
}
if (Physics.Raycast(ray2, out hit, Mathf.Infinity))
{
if (hit.transform.gameObject.name == "playa")
{
player.AddForce((hit.collider.gameObject.transform.position - hit.point).normalized *10 , ForceMode.VelocityChange);
Debug.Log("Playa hit");
}
}
}
}
Answer by WarmedxMints · Feb 28, 2019 at 03:31 PM
Update is called by Unity every frame. You are raycasting in Update so it is going to happen every frame.
You need to raycast only when you wish. Maybe on a mousedown event?
Im an idiot, I misplaced the if brackets thanks for the advice u have been very helpful
Your answer
Follow this Question
Related Questions
Physics.Raycast Not Working... Kinda 0 Answers
Raycast is offsetting object 1 Answer
Do touch on point where ray hits 0 Answers
How to cast a Ray using local pivot of an object? 1 Answer
Raycast Hit suddently stopped working 0 Answers