- Home /
Homing mechanic, help!
So I want my player character to jump, then home towards an enemy if the jump button is pressed again. So far, this is the code I've got, and for now I'm just trying to get the Physics2D.OverlapCircleAll to work. However I'm not able to get the method to recognize a box in my environment which has been placed in the "Enemy" layer. Moreover, if I increase the radius of the OverlapCircleAll then I detect four objects in the returned list, which doesn't make sense to me because I only have one object in my environment that exists in the "Enemy" layer. Can someone help me out here? I'm really new to Unity so I don't know if I'm missing some simple conventions or something.
if (Input.GetButtonDown ("Jump") && grounded) {
print ("Jump");
velocity.y = jumpTakeOffSpeed;
homingColliderList = Physics2D.OverlapCircleAll (rb2d.position,homingRadius,LayerMask.NameToLayer("Enemy"),-1,1); // Mess around with these parameters later
print("Length of Collider List " + homingColliderList.Length);
} else if (Input.GetButtonUp ("Jump")) {
if (velocity.y > 0) {
velocity.y = velocity.y * .5f;
}
}
if (Input.GetButtonDown ("Jump") && !grounded) {
print (homingColliderList.Length);
if ((int)homingColliderList.Length != 0) {
print ("HomingList has objects!");
print (homingColliderList [0].gameObject.tag);
//homingTarget = Physics2D.Raycast (rb2d.position, rb2d.position - homingColliderList[0].attachedRigidbody.position,homingRadius,9,1f,100f);
if (homingTarget != null) {
if (homingColliderList[0].gameObject.tag == "Enemy") {
}
Answer by Eno-Khaon · May 21, 2018 at 05:52 AM
You need to change the way you're using your LayerMask in Physics2D.OverlapCircleAll().
A LayerMask allows you to choose many layers based on their bits, rather than being limited to using only a single layer at a time.
To demonstrate how this works, consider this: Let's say you want a Raycast to hit objects only on Layers 3 and 6. That would basically look like...
Layer#: 76543210
vvvvvvvv
Value: 01001000
| |
Value per bit: 1| |
written 26 |
vertically 843 |
21|
68
4
2
1
Integer value: 72 (64 + 8)
These values are effectively (26 + 23).
So how do you make use of the LayerMask with this in mind? Well, that's the value in a bit shift. You know which bit your Layer is (LayerMask.NameToLayer("Enemy")), so to use it, you need to shift the bits over. This is where the layout I described above comes into play. The larger value comes first and the smallest value comes last, so a bitwise operation using layers 3 and 6 could look like:
(1 << 3) + (1 << 6)
00000001
<--- Move left 3
00001000
00000001
<--- Move left 6
01000000
00001000
+ 01000000
= 01001000
Or, in the context you'll be using bit shifts specifically:
Physics2D.OverlapCircleAll (rb2d.position,homingRadius,1 << LayerMask.NameToLayer("Enemy"),-1,1);
That said, it might be wise to save the layer number from "NameToLayer()" as a variable during Start, since that won't really change during gameplay.