2D Gun following rotation problem
I'm trying to implement an enemy that patrols left and right, changes direction when it hits specific invisible checkpoints. The enemies have a child gun object that follows the player spaceship and fires when in range. This works fine until the enemy hits the their checkpoint and change the transform.localscale direction. The following attached gun that "follows" the player inverts it's direction until it once again changes direction back to original. End result is that when enemy moves right, it follows perfectly, when it moves left, it's follow inverts.
Enemy Move Script:
public class enemypatrol : MonoBehaviour {
public float moveSpeed;
public bool moveRight;
Rigidbody2D enemyrb2d;
public Transform wallCheck;
public float wallCheckRadius;
public LayerMask whatIsWall;
public bool hittingWall;
// Use this for initialization
void Start () {
moveRight = true;
enemyrb2d = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
hittingWall = Physics2D.OverlapCircle(wallCheck.position, wallCheckRadius, whatIsWall);
if (hittingWall)
{
moveRight = !moveRight;
}
if (moveRight)
{
transform.localScale = new Vector3(1f, 1f, 1f);
enemyrb2d.velocity = new Vector2(moveSpeed, enemyrb2d.velocity.y);
}
else {
transform.localScale = new Vector3(-1f, 1f, 1f);
enemyrb2d.velocity = new Vector2(-moveSpeed, enemyrb2d.velocity.y);
}
}
Gun Rotation Script
public class gunrotation : MonoBehaviour {
public Transform target;
public int rotationOffset = -90;
// Use this for initialization
void Start () {
}
void Update () {
Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
Vector3 difference = target.position - transform.position;
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotZ + rotationOffset);
}
Cant you change direction without changing local scale? That is what makes you have this issue
Yes that solves the gun rotation problem. $$anonymous$$y enemy sprite isn't flipping to face other direction in that case which I'll have to fix somehow
There might be some other clever way of doing this but the easiest would be ta make 2 animations. One moving right and one moving left and use the animation system to change the states.
This way you change the actual image and not the transform
Your answer
Follow this Question
Related Questions
Player Respawn Problem, Bullets dont move! [C#] 0 Answers
Shoot at mouse cursor 0 Answers
2D shooting script fixed camera 2 Answers