- Home /
Question by
Krautbytes · Dec 30, 2017 at 06:49 PM ·
rotationpositionobjectmouse
Rotate a thrown spear to Mouse Position (2d top down game)
Hello,
I want to rotate the top of a thrown spear to the mouse´s direction.
Thats my code so far. it rotates but not the way i want it to ... im new at coding and seriously need help please. im sitting on it for hours ... :(
(void throwSpear() is executed in another Script)
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(Rigidbody2D))] public class SpearThrow : MonoBehaviour {
[SerializeField]
private float speed;
private Rigidbody2D myRigidbody;
private Vector2 direction;
private float throwingTime = 2;
private bool spearThrowing = false;
private float spearThrown;
// Drag Spear Prefab to SpearThrow Script
[SerializeField]
private GameObject spearPrefab;
// Use this for initialization
void Start () {
myRigidbody = GetComponent<Rigidbody2D>();
// Throw spear To mouse position
direction = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, speed * Time.deltaTime);
}
private void FixedUpdate()
{
myRigidbody.velocity = direction * speed;
if (Time.time > spearThrown + throwingTime && spearThrowing == true)
{
Destroy(GameObject.FindWithTag("spear"));
}
}
// Update is called once per frame
void Update () {
}
public void throwSpear()
{
// Throw Spear
Instantiate(spearPrefab, transform.position, Quaternion.Euler((Input.mousePosition) - transform.position));
spearThrowing = true;
spearThrown = Time.time;
}
}
Comment