- Home /
Anchored Rotation with Gradual Movement
Hi, I just started my first game. The protagonist can extend his tongue and eat up any objects in the path to become stronger. The problem is that the tongue will be rolling out slowly from his mouth and its rotation must be anchored to the mouth (mouth is the pivot of rotation) whilst extending forward toward cursor position in a straight line. My current implementation takes the tongue of full length and place it above mouth. I plan to hide the portion above the mouth with a mask and when a button is pressed, the tongue would move down (this is a 2D top-down game) , appear on screen and can be rotated freely. The pivot of rotation is not the mouth though, I tried using a pivot object as parent but it doesn't seem to work (I tried setting position handler to pivot or center and so on but to no avail). Is there a better way of achieving the said effect and do you know what's wrong with the rotation? Thanks. Here is my code even if it looks really terrible. (the script is placed in pivot, parent of the tongue)
public class TongueAction : MonoBehaviour
{
public Transform firePoint;
public float offset;
public float tonguelength = 0.5f;
private Vector3 mousePosition;
public GameObject projectile;
private Vector2 direction;
public float speed = 0.5f;
private Rigidbody2D rb2d;
private void Start()
{
rb2d = GetComponentInChildren<Rigidbody2D>();
}
void Update()
{
Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
projectile.transform.rotation = Quaternion.Euler(0f, 0f, rotZ + offset);
if (Input.GetMouseButton(0))
{
shootTongue();
} else
{
rb2d.velocity = Vector2.zero;
}
}
void shootTongue()
{
projectile.SetActive(true);
mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); //the destination we move to;
direction = mousePosition - transform.position;
if (Mathf.Sqrt(Mathf.Pow(direction.x, 2) + Mathf.Pow(direction.y, 2)) > tonguelength)
{
rb2d.velocity = Vector2.zero;
} else
{
direction = (mousePosition - transform.position).normalized;
rb2d.velocity = new Vector2(0, direction.y * speed * Time.deltaTime);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
Debug.Log("Collided");
projectile.SetActive(false);
}
}
Your answer
Follow this Question
Related Questions
Make movement of an object independant. 1 Answer
how to make an object move towards it's rotation a set amount as a child in 2d 0 Answers
Help with rotating a sprite with mouse. 2 Answers
Trying to get the player to face the direction of a touch 1 Answer
Character still walking when no key is already pressed 1 Answer