So I’m completely new to C# and scripting in general, I have no idea how to do this. I’ve googled my problem and found tons of answers, none of which helped me. I have a sprite in a cage and I want the sprite to go back and forth while flipping it’s X. This is a 2D game. The sprite’s name is TrappedPerson1 and I have no official name for the script. Thanks and sorry in advance!
I’m not sure what you want but if you want to flip a sprite’s direction, set x scale to -1.
Moving left and right itself should be simple. Look up some tutorials.
- Add a component Rigidbody2D to your gameobject and set its body type to kinematic.
- Create a script OfficialName and put it on your gameobject
using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
public class OfficialName : MonoBehaviour
{
private Rigidbody2D rb;
private float speed = 1f;
private float amplitude = 3f;
private Vector3 originalScale;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
originalScale = transform.localScale;
MoveToDirection(Vector2.right);
}
private void FixedUpdate()
{
if (transform.position.x > amplitude)
{
MoveToDirection(Vector2.left);
}
else if (transform.position.x < -amplitude)
{
MoveToDirection(Vector2.right);
}
}
private void MoveToDirection(Vector2 direction)
{
rb.velocity = direction * speed;
transform.localScale = new Vector3(direction.x < 0 ? -originalScale.x : originalScale.x, originalScale.y,
originalScale.z);
}
}
ok I’ll try this thanks!