Home > front end >  Difficulties flipping a collider in Unity when attacking
Difficulties flipping a collider in Unity when attacking

Time:10-27

I am working on a small game for a school project, in which my player needs to attack enemies in a level. My plan is to have a collider that is enabled in an attached script, and then disabled when the attack is done. My current problem is that that the collider does not flip the way it is supposed to, it seems to flip directly on the overall x axis instead of flipping in the x axis related to the player. It is a child of the player so I am clueless as to why it is doing this. Any solutions or other approaches would be greatly appreciated. I will attach the current script that controls the collider below.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class VerticalSword : MonoBehaviour
{
    //Variables use to active the colliders
    Collider2D AttackColliderVertical;

    //Variables for the location of the collider
    Vector2 attackOffset;

    private void Start()
    {
        AttackColliderVertical = GetComponent<Collider2D>();
        attackOffset = transform.position;
        AttackColliderVertical.enabled = false;
    }

    public void FixedUpdate()
    {
        attackOffset = transform.position;
    }

    public void AttackUp()
    {
        AttackColliderVertical.enabled = true;
        if (attackOffset.y > 0)
        {
            transform.position = attackOffset;
        }
        else if (attackOffset.y < 0)
        {
            transform.position = new Vector2(attackOffset.x, (attackOffset.y * -1)); //I think the problem is somewhere in this if and else if statement
        }
        print("Attack up successful"); //Error checking (This works when run)
    }

    public void AttackDown()
    {
        AttackColliderVertical.enabled = true;
        if (attackOffset.y > 0)
        {
            transform.position = new Vector2(attackOffset.x, (attackOffset.y * -1));
        }
        else if (attackOffset.y < 0)
        {
            transform.position = attackOffset; //I think the problem is somewhere in this if and else if statement
        }
        print("Attack down successful"); //Error checking (This works when run)
    }

    public void StopAttack()
    {
        AttackColliderVertical.enabled = false;
    }
}

CodePudding user response:

Use transform.localPosition, not transform.position (that's its world space position). You need to change it everywhere in this script; the Start() function and the two attack functions

  • Related