How to make a thrown object land on a certain point e.g a thrown spear landing on its tip
https://i.imgur.com/0ur0USW.gifv
This is a gif of what I'm talking about. I want my swear to land on its tip when thrown but I have no idea how to do that. I have posted my code below.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.Scripting.APIUpdating;
public class movement : MonoBehaviour
{
Rigidbody2D rb;
Vector3 velocity;
private Vector3 _initialPosition;
[SerializeField] private float _launchPower = 500;
private void Awake()
{
_initialPosition = transform.position;
}
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
if(transform.position.y > 12.5 ||
transform.position.y < -12.5 ||
transform.position.x > 15 ||
transform.position.x < -15)
{
string currentSceneName = SceneManager.GetActiveScene().name;
SceneManager.LoadScene(currentSceneName);
}
}
private void OnMouseDrag()
{
Vector3 newPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position = new Vector3(newPosition.x, newPosition.y);
}
private void OnMouseUp()
{
Vector2 directionToInitialPosition = _initialPosition - transform.position;
GetComponent<Rigidbody2D>().AddForce(directionToInitialPosition * _launchPower);
GetComponent<Rigidbody2D>().gravityScale = 1;
}
}
Answer by streeetwalker · Sep 18, 2020 at 08:53 AM
@KH0RAS, that is fairly easy to do:
each FixedUpdate frame get the Rigidbody2D.velocity of your spear. Use that to calculate the angle it is moving at and set the Rigidbody2D.rotation to that angle
This code assumes have the forward direction of your spear object in the +x direction, and rb is a reference to the Rigidbody2D component of the spear:
rb.rotation = Mathf.Atan2( rb.velocity.y, rb.velocity.x ) * Mathf.Rad2Deg;
this will ensure the tip of the spear is always pointing in the direction it is moving.
Your answer
Follow this Question
Related Questions
How to make a thrown object land on a certain point e.g a thrown spear landing on its tip 0 Answers
Try part of C# not being Read 1 Answer
Rotating Movement with Acceleration problem 1 Answer
Keeping Score out of Update Function 1 Answer
how do i keep an item destroyed when i change the scene c# 0 Answers