- Home /
How to flip my Bullet with my Sprite
So I have my parent (which is the sprite) and I have my child (firepoint of the bullet) but I don't know how to synch them to flip together, when my character flips the fire position stays in the same pos.
Heres the shoot script attached to the fire point (which is the child of the sprite)
// Shoot needs to know the direction, so we just ask the renderer if we are flipped
// Link the player sprite renderer to this in inspector
[SerializeField] public SpriteRenderer mySpriteRenderer;
private void Update()
{
if (Input.GetKeyDown(KeyCode.K))
{
GameObject go = Instantiate(projectilePrefab, transform.position, transform.rotation);
Rigidbody2D rb2d = go.GetComponent<Rigidbody2D>();
// Lets get our direction from renderer
int facing = mySpriteRenderer.flipX == true ? -1 : 1;
rb2d.velocity = transform.TransformDirection(new Vector3(20f, 0, 5f)) * facing;
}
}
}
Answer by I_Am_Err00r · Aug 20, 2019 at 02:02 PM
You need to better define what the player direction is on the player; I'm guessing you don't have a script on your player that manages the different states; the easiest way to define direction is through the player movement, and this script should be included into whatever script you have for player movement.
I have a solution, it's based on variables you defined in this script though and might need you to tweak the variable names:
public bool facingLeft;
private void Start()
{
if(facingLeft == true)
{
facingLeft = false;
Flip();
}
}
private void FixedUpdate()
{
CheckDirection();
}
public void CheckDirection()
{
if(facingLeft != true && rb2d.velocity.x < 0)
{
Flip();
}
else if(facingLeft == true && rb2d.velocity.x > 0)
{
Flip();
}
}
private void Flip()
{
facingLeft = !facingLeft;
Vector2 theScale = new Vector2();
theScale = gameObject.transform.localScale;
theScale.x *= -1;
gameObject.transform.localScale = theScale
}
If you set that up correctly, all children objects will conform to the parent and flip appropriately; I've also set this up so that if you want to have the character facing left at the start, you just check that public bool I set and that will ensure that when you load your player, it will face the direction you have chosen through that bool.
Since I added this to my script I'm stuck in my jump animation and can no longer jump. Please help =)
If you are having trouble with your jump I can say with confidence that it is unrelated to this solution and purely coincidental if you noticed the problem when you added this; this script purely faces the sprite in the direction in which they are moving based on velocity value from the rigidbody2D, it only reads values from the rigidbody2d componenet and it does not change any of the values that would somehow affect your jump.
If you want help, please post a new question with what is going on, provide the script that contains the jump command, and I'll take a look at it from there.