- Home /
Question by
Alphacreations · May 24, 2020 at 07:17 AM ·
knockback
object always "knockbacking" wrong way?
Hello fellow unity members,
I made a punching bag in my game and it registers the wrong movement
using UnityEngine;
public class EnemyStuff : MonoBehaviour
{
public Animator animator;
public int maxHealth = 300;
int currentHealth;
private Rigidbody2D rb;
public LookAtCharacter LookAtCharacter;
void Start()
{
currentHealth = maxHealth;
rb = GetComponent<Rigidbody2D>();
LookAtCharacter = GameObject.Find("Punching bag").GetComponent<LookAtCharacter>();
}
public void TakeDamage(int damage)
{
currentHealth -= damage;
// play hurt animaton
if (damage == 10)
{
animator.SetTrigger("jab");
if (LookAtCharacter.left == false)
{
rb.AddForce(new Vector2(150, 0));
}
else if (LookAtCharacter.right == false)
{
rb.AddForce(new Vector2(-150, 0));
}
}
} }
I have referenced the left and right boolean from this script
public class LookAtCharacter : MonoBehaviour
{
public bool facingRight = false;
private Transform target;
public float speed;
public bool right;
public bool left;
public void Start()
{
target = GameObject.FindGameObjectWithTag("Player").transform;
left = true;
right = false;
}
private void Flip()
{
Vector3 scale = transform.localScale;
scale.x *= -1;
transform.localScale = scale;
facingRight = !facingRight;
}
public void Update()
{
right = target.position.x > transform.position.x && !facingRight;
left = target.position.x < transform.position.x && facingRight;
if (Vector3.Distance(target.position, transform.position) < 600)
{
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
if (right == true) //if the target is to the right of enemy and the enemy is not facing right
Flip();
if (left == true)
Flip();
}
if (Vector3.Distance(target.position, transform.position) < 20)
{
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
}
else
{
transform.Translate(Vector2.right * speed * Time.deltaTime);
}
}
}
I also added a chase character function in the script above for fun. The problem is the punching bag is always getting punched towards the right. The animation works smoothly which is weird because the animation relies on which way the payer is to the punching bag. Can somebody please help?
Comment
Answer by TheElectroResistance · May 24, 2020 at 07:39 AM
Have you tried changing the direction of the force. @Alphacreations
if (LookAtCharacter.left == false)
{
rb.AddForce(new Vector2(-150, 0));
}
else if (LookAtCharacter.right == false)
{
rb.AddForce(new Vector2(150, 0));
}
@TheElectroResistance That doesn't work, it just makes the punching bag always go left now
Your answer
