• 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 /
avatar image
0
Question by Aladine · Oct 16, 2013 at 03:20 PM · collisiontopdown

the right way of making 2d 4 direction collision

Hello everyone, i always faced numerous problems when it comes to create a top-down game (zelda,pokémon,etc..) because of the collision detection, and the thing is not that i can't tell which direction the player is hitting, the problem is how to apply that, i've tried many times (even before start using unity) and i always faced some issues, it never worked perfectly, even when it seems that everything is doing fine, sometimes it just ignore the collision and go right through the wall, i have uploaded a unity package to test it by your own and tell me what is wrong Link

how ever if you can find out the problem with just reading the codes here, then here is my player class : Pastebin for better readability

thank you very much

EDIT: whydoidoit: Embedded code in question

 using UnityEngine;
 using System.Collections;
  
 public class J2PlayerMovement : MonoBehaviour
 {
        
        
         public float            speed ;                         // speed
         public float            ySpeed, yDir;           // Y direction & x speed
         public float            xSpeed, xDir;           // X direction & x speed
         public float            maxDist ;                       // max distance between ray origin and hit point
         private RaycastHit      hit ;
         private Transform       myTransform;
         [HideInInspector]
         public Vector3 myPos;
         public float tmpYDir,tmpXDir;
         void Start ()
         {
        
                 myTransform = transform;
                 myPos = myTransform.position;
                 ySpeed = xSpeed = speed;
                 float tmpYDir =1;
         }
        
         // Update is called once per frame
  
         void Update ()
         {
                 collision ();
                 //move up down
                 yDir = Input.GetAxisRaw ("Vertical");
                 myPos.y += (ySpeed * yDir) * Time.deltaTime;
                 //move left right
                 xDir = Input.GetAxisRaw ("Horizontal");
                 myPos.x += (xSpeed * xDir) * Time.deltaTime;
                 //apply
                 myTransform.position = myPos;
                
                
         }
  
         //check for collision
         void collision ()
         {
                
                
                 if(Input.GetKey(KeyCode.UpArrow)){
                         tmpYDir = 1;
                 }
                 if(Input.GetKey(KeyCode.DownArrow)){
                         tmpYDir = -1;
                 }
                
                 //make 3 rays upon the object
                 for (int i = -1; i<2; i++) {
                         //set ray setting (3 rays above/under the player)
                         Ray ray = new Ray (
                                 new Vector3 (
                                                 myTransform.position.x + myTransform.localScale.x / 2 * i,
                                                 myTransform.position.y + (1 * Mathf.Sign (tmpYDir) * myTransform.localScale.y / 2), 0),
                                                 new Vector3 (0, Mathf.Sign (tmpYDir), 0)
                                 );  
                         //check if one of those rays hit something
                         if (Physics.Raycast (ray, out hit, Mathf.Abs (tmpYDir) + maxDist)) {
                                 Debug.DrawRay (ray.origin, ray.direction, Color.green);
                                 //calculate the distance between ray origin and the hit point
                                 float dist = Vector3.Distance (ray.origin, hit.point);
                                 //if distance reach the limit
                                 if (dist < maxDist) {
                                         //stop moving
                                         ySpeed = 0;
                                         Debug.DrawRay (ray.origin, ray.direction, Color.red);
                                 }
                         }
                         //if you're not touching anything
                         else {
                                 ySpeed = speed;
                                 Debug.DrawRay (ray.origin, ray.direction, Color.green);
                         }
                 }
        
                 /*********************************/
                 /*SAME ABOVE PRINCIPLE FOR THE 2 OTHER DIRECTIONS*/
                
                 /*********************************/
                 if(Input.GetKey(KeyCode.RightArrow)){
                         tmpXDir = 1;
                 }
                 if(Input.GetKey(KeyCode.LeftArrow)){
                         tmpXDir = -1;
                 }
                
                 for (int i = -1; i<2; i++) {
                         Ray ray = new Ray (
                                 new Vector3 (
                                                 myTransform.position.x + (1 * Mathf.Sign (tmpXDir) * myTransform.localScale.x / 2),
                                                 myTransform.position.y + myTransform.localScale.y / 2 * i, 0),
                                                 new Vector3 (Mathf.Sign (tmpXDir), 0, 0)
                                 );  
                         if (Physics.Raycast (ray, out hit, Mathf.Abs (tmpXDir) + maxDist)) {
                                 Debug.DrawRay (ray.origin, ray.direction, Color.green);
                                 float dist = Vector3.Distance (ray.origin, hit.point);
                                 if (dist < maxDist) {
                                         xSpeed = 0;
                                         Debug.DrawRay (ray.origin, ray.direction, Color.red);
                                 } else {
                                 xSpeed = speed;
                                 Debug.DrawRay (ray.origin, ray.direction, Color.green);
                                
                                 }
                         } else {
                                 Debug.DrawRay (ray.origin, ray.direction, Color.green);
                                 xSpeed = speed;
                                
                         }
                 }
         }
 }


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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

14 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

Related Questions

Picking up a coin in 2D 0 Answers

Rigidbody2D characters push each other 0 Answers

Generating 2D collisions for maze 0 Answers

XP and Collision in Unity2D 0 Answers

How to fix, that every clone changes color, if I shoot at only one clone? 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