本文主要是介绍Unity 2D游戏中的抛物运动,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
using UnityEngine;public class ProjectileMotion : MonoBehaviour
{//投掷物[SerializeField] private GameObject bomb;//力[SerializeField] private float force;[SerializeField] LineRenderer lineRenderer;private float theta;//速度private float velocity;Vector3[] ves;private void Start(){lineRenderer.positionCount = 100;ves = new Vector3[100];}Vector2 dir;private void Update(){//弧度float yLength = Camera.main.ScreenToWorldPoint(Input.mousePosition).y - transform.position.y;float xLength = Camera.main.ScreenToWorldPoint(Input.mousePosition).x - transform.position.x;//返回其切线为两个浮点数的商的角度。theta = Mathf.Atan2(yLength, xLength);dir = ((Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition) - (Vector2)transform.position).normalized;//速度velocity = (dir * force).magnitude;if (Input.GetKeyDown(KeyCode.J)){GameObject Projectile = Instantiate<GameObject>(bomb, transform.position, Quaternion.identity);Projectile.GetComponent<Rigidbody2D>().velocity = dir * force;}for (int i = 0; i < 100; i++){float t = i * 0.05f;float x = velocity * t * Mathf.Cos(theta) + transform.position.x;float y = velocity * t * Mathf.Sin(theta) + 0.5f * Physics2D.gravity.y * t * t + transform.position.y;ves[i] = new Vector3(x, y, 0);}lineRenderer.SetPositions(ves);}
}
这篇关于Unity 2D游戏中的抛物运动的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!