- Home /
Linecast Detecting Initial Collision Correctly, Need it to Stay Until Line Doesn't Intersect
Currently have a system in place where the player has a linecast starting from it's position plus an offset (so it doesn't detect the player) and an end position. Upon line intersection the initial collision is detected, though in subsequent frame no longer identified as an active collision, and therefore ignored, until a separate movement/collision is caused.
As I'd like the Player to be able to interact with any collider that's within the linecast, I really need the collision detection to remain detecting until the player moves the object outside the line's range, so that a Player can continue pressing a button and having the parallel object respond, even when it's not the initial collision.
void FixedUpdate() {
// enum
Buttons direction = playerState.getDirection ();
// cast a line in the direction of the player, if object touches the line, load object into interactionInfo
RaycastHit2D interactionInfo = Physics2D.Linecast(UsefulFunctions.position2d (transform) + UsefulFunctions.vectorAdd (direction, 16),
UsefulFunctions.position2d (transform) + UsefulFunctions.vectorAdd (direction, 50));
if(interactionInfo.collider != null) {
// if a button is pressed, check that it isn't None
if (activeButton != Buttons.None) {
// identify the mapObject and execute the command attached to the button
interactionInfo.collider.gameObject.GetComponent<MapObject>().Execute(activeButton);
}
}
}
The main issue is Linecast() only detecting upon initial collision. I've also tried the implementation above in Update() - same effect, and utilized LineCastNonAlloc(), which kept detecting collision, though continued to do so upon leaving object, which isn't my intent either. Also set the player's RigidBody2D Collision Detection to Continuous though no luck.
Any and all help / advice would be significantly appreciated. Thanks!
Answer by dokisoft · Apr 28, 2017 at 06:16 PM
Got it working through the addition of isTouching(), as can be seen below
if (interactionInfo.collider != null) {
_collider = interactionInfo.collider;
}
if(_collider != null && _collider.IsTouching(thisGameObjCollider)) { ... }
Accepting this as answer as it works as desired. If however anyone has a better implementation, please don't hesitate to share :)