crabcrabcam
crabcrabcam

Reputation: 219

Object target radius checking in Unity

I'm trying to make an attacking sword thing that moves between 3 points. The main place in the characters hand, the top of the swing and the bottom of the swing. After that it goes back to the hand.

I used the general "ground check for jumping" code and modified it a bit because using "Move towards" in a loop never quite hit exactly for changing to the next stage.

Both errors are on the "reachedTarget" line;

The best overloaded method match for `UnityEngine.Physics2D.OverlapCircle(UnityEngine.Vector2, float, int)' has some invalid arguments

Argument `#3' cannot convert `UnityEngine.Vector3' expression to type `int'

Here's the code.

void TargetCheck(GameObject target)
{
    //Returns true when the sword is over the target
    reachedTarget = Physics2D.OverlapCircle(transform.position, 0.1f, target.transform.position);
}

I'm not quite sure what I'm doing wrong here. Thanks for any help :)

Upvotes: 1

Views: 1455

Answers (2)

Fredrik
Fredrik

Reputation: 5108

"cannot convert x expression to type y" always means you're trying to enter something of type x where you need type y. For instance: int number = "hello world"; will not work. You're trying to convert int to string

In your case you're trying to enter an int LayerMask with target.transform.position. See documentation on OverlapCircle

If you're not sure about which LayerMasks and how to bitshift, declare a public LayerMask layermask; and let Unity serialize it. This will give you checkbox buttons to fill in which Layers.

Edit: it appears Vector3.Distance was what OP wanted!

Upvotes: 1

Hexo
Hexo

Reputation: 528

You probably dont need the third parameter. That should be the layer of whose Objects you want to collide with. Make sure it's the layer id of your target.

Afterwards reachedTarget should probably be compared with target's Collider2D component. If it matches - you've got a hit.

Edit for lazy people - should be something like:

void TargetCheck(GameObject target)
{
    //Returns true when the sword is over the target
    var CollidedWith = Physics2D.OverlapCircle(transform.position, 0.1f, *LayerYouWantToCollideWith*);

    var TargetCollider2D = target.GetComponent<Collider2D>();
    bool CollidedWithTarget = CollidedWith == TargetCollider2D;
}

PS: you should probably get the Collider2D component of your target beforehand and store it somewhere..

Upvotes: 0

Related Questions