- Home /
Raycast hits only one frame
Hi, I'm kinda new to unity so I'm asking ya'll for help on this.
My problem is that transform.rotation only happens on the first frame of the Raycast hitting the ground, but I'm trying to set the object's rotation relative to that surface for as long as the object is grounded.
I'm working with 2D btw
Any help would be appreciated!
void RotateSprite(ref Vector2 moveAmount) { float rayLength = Mathf.Abs(moveAmount.y) + skinWidth;
for (int i = 0; i < verticalRayCount; i++)
{
Vector2 rayOrigin = raycastOrigins.bottomCenter;
rayOrigin += Vector2.down * (verticalRaySpacing * i + moveAmount.x);
RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.down, rayLength, collisionMask);
Debug.DrawRay(rayOrigin, Vector2.down, Color.magenta);
if (hit && collisions.below)
{
float slopeAngle = Vector2.Angle(hit.normal, Vector2.up);
sprite.transform.rotation = Quaternion.AngleAxis(-slopeAngle, Vector3.forward);
rayLength = hit.distance;
}
else
{
sprite.transform.rotation = Quaternion.AngleAxis(0, Vector3.forward);
}
}
}
Have you considered looping this through frames, like in the Update() function? You can then check if the object is grounded before calling it.
Answer by Sinterklaas · Jun 21, 2021 at 01:35 PM
Raycasting functions only check collision at the moment that they're called. They need to be called every frame if you want them to be in effect every frame. Like by putting them in the Update function, which gets called once per frame.
In general this is a good rule-of-thumb: if you want something to happen constantly, you need to run the appropriate code constantly.
Yes I thought about that! Couldn't I use some kind of coroutine instead?
Also it is impossible to pass parameters through update, so I'll need to research on this
you cannot pass things through update. instead, you would create a variable on your script, and write/read to it each update.
You could use a coroutine, but that function would still run every frame, so you wouldn't really gain anything from doing so.
As for Update() and parameters, you use member variables instead, either declared as public or as private/protected with a [SerializeField] attribute. These variables can then be changed from the inspector, and serve as a stand-in for function parameters. The same goes for other event functions, like Awake(), Start() or FixedUpdate().
Huge thanks to yall! I'll be looking into this :)
Your answer
Follow this Question
Related Questions
What's wrong with my RaycastHit2D? 1 Answer
I don't get Raycasts 0 Answers
Raycast detects 2/3 of a collider? 0 Answers