Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
0
Question by SirSmileX · Jul 07, 2018 at 12:34 PM · 2draycastphysics2ddistanceraycasthit2d

Checking for Raycast distances not working as expected.

Hey Guys,


I am programming a 2D game where you can move a sprite in a room and can dash from wall to wall by clicking in the direction you want to go. Everything is working fine and I'm onto optimising things. One of which is that you can click behind a wall the character is attachted to and it will try to go there.


My solution to this is to send Raycasts from the character towards the mouse position and check whether a the hit occurs after a certain distance. One Ray however does not seem to work especially around corners. So I thought of making a row of raycast which individually fire towards the mouse click with a maxDistance. Then I add them up and see if they are lower than the value that they would have if every Ray fired without being blocked. If so then some ray must have been obstructed and not allow for move.


Somehow it does not work and maybe you can figure out what it is. Maybe it has something to do with calculating the position of every ray and the spacing. Important parts are the FixedUpdate and ValidateMove Functions.


Looking forward to your suggestions!


SirSmileX


 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class Movement : MonoBehaviour {
 
     public float dashSpeed = 10f;
 
     public bool canMove = true;
 
     public int rayCount = 5;
     public float maxWallDistance = 1.0f;
 
     private bool isClicked = false;
     private Rigidbody2D rb;
     private GameManager gm;
     private BoxCollider2D notClickable;
     private RaycastHit2D[] hits;
 
     void Start ()
     {
         rb = GetComponent<Rigidbody2D>();
         gm = Camera.main.GetComponent<GameManager>();
         notClickable = GetComponentInChildren<BoxCollider2D>();
     }
 
     void FixedUpdate ()
     {
         if (Input.GetMouseButtonDown(0) && canMove)
         {
             if (!isClicked) {
                 if (ValidateMove())
                 {
                     canMove = false;
                     notClickable.enabled = false;
                     
                     Vector2 direction = (Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position);
                     rb.AddForce(direction.normalized * dashSpeed);
 
                     float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
                     transform.rotation = Quaternion.AngleAxis(angle - 90f, Vector3.forward);
                 }
             }
         }
     }
 
     private bool ValidateMove()
     {
         Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
 
         hits = new RaycastHit2D[rayCount];
 
         float totalDistance = 0.0f;
 
         float spacing = 0.5f / rayCount;
         for (int i = 0; i < rayCount; i++)
         {
             Vector2 position = new Vector2(transform.position.x - 0.25f + spacing * i, transform.position.y) * transform.up;
             hits[i] = Physics2D.Raycast(position, (mousePosition - position).normalized, maxWallDistance + 0.01f);
             totalDistance += hits[i].distance;
         }
         if (totalDistance <= maxWallDistance * (float)rayCount)
         {
             return false;
         }
         return true;
     }
 
     private void OnCollisionEnter2D(Collision2D collision)
     {
         if (collision.gameObject.CompareTag("isEnvironment"))
         {
             rb.velocity = Vector2.zero;
             Vector2 contactPoint = collision.contacts[0].normal;
             transform.rotation = Quaternion.FromToRotation(Vector2.up, new Vector2(contactPoint.x, contactPoint.y));
             notClickable.enabled = true;
             canMove = true;
         }
     }
 
     private void OnTriggerEnter2D(Collider2D collision)
     {
         if (collision.gameObject.CompareTag("isBlob"))
         {
             Destroy(collision.gameObject);
             gm.score++;
         }
 
         if (collision.gameObject.CompareTag("isBomb"))
         {
             rb.velocity = Vector2.zero;
             StartCoroutine(gm.Restart());
         }
     }
 
     private void OnMouseOver()
     {
         isClicked = true;
     }
 
     private void OnMouseExit()
     {
         isClicked = false;
     }
 }



Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

0 Replies

· Add your reply
  • Sort: 

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

206 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Rigidbody blocking raycasts 2D 0 Answers

Is it possible to add Angle to Raycast2D? 1 Answer

Racasthit2d range not working 1 Answer

RaycastHit2D ground detection 1 Answer

Three out of four of these raycasts aren't working 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges