- Home /
Question by
coding_frog · May 12, 2021 at 09:53 PM ·
c#raycastbeginner
Problems with raycast
So I wanted to add a groundcheck to my script so I can prevent multiple jumping in the air. I don't understand several things now: 1 I can't see the raycast. Even if I enable gizmos. 2 Since I added the GroundLayerMask stuff, the jump is no longer executed when I swipe over the screen. An answer would be great. Its my first Unity project. I'm actually pretty sure it's a simple/stupid error, as with my last question. But I cant find the error.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Touch_Input : MonoBehaviour
{
[SerializeField] private LayerMask GroundLayerMask;
public float jumpForce;
public float maxSwipeTime;
public float minSwipeTime;
public float MinSwipeDistance;
private float SwipeTime;
private float SwipeLength;
private float SwipeStartTime;
private float SwipeEndTime;
private Rigidbody2D rb;
private BoxCollider2D boxCollider2d;
private Vector2 SwipeStartPos;
private Vector2 SwipeEndPos;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
boxCollider2d = GetComponent<BoxCollider2D>();
}
private void Update()
{
swipeTest();
}
void swipeTest()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began)
{
SwipeStartTime = Time.time;
SwipeStartPos = touch.position;
}
else if (touch.phase == TouchPhase.Ended)
{
SwipeEndTime = Time.time;
SwipeEndPos = touch.position;
SwipeTime = SwipeEndTime - SwipeStartTime;
SwipeLength = (SwipeEndPos - SwipeStartPos).magnitude;
if (SwipeTime < maxSwipeTime && SwipeLength > MinSwipeDistance)
{
Debug.Log("Player is swiping.");
SwipeControl();
}
}
}
}
void SwipeControl()
{
Vector2 Distance = SwipeEndPos - SwipeStartPos;
float xDistance = Distance.x;
float yDistance = Distance.y;
if (Distance.x < Distance.y && isGrounded())
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
Debug.Log("Player is jumping.");
}
}
private bool isGrounded()
{
// float extraHeightTest = .01f;
RaycastHit2D raycastHit = Physics2D.Raycast(boxCollider2d.bounds.center, Vector2.down, boxCollider2d.bounds.extents.y, GroundLayerMask /*+ extraHeightTest*/);
Color rayColor;
if (raycastHit.collider != null)
{
rayColor = Color.green;
}
else
{
rayColor = Color.red;
}
Debug.DrawRay(boxCollider2d.bounds.center, Vector2.down * (boxCollider2d.bounds.extents.y /*+ extraHeightTest*/));
return raycastHit.collider != null;
}
}
Comment
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Updating line positions with reflections 1 Answer
How do I make it know what it's hitting? 3 Answers
How can I make my player unable to jump up walls? 2 Answers
Multiple Cars not working 1 Answer