Skip to content

Instantly share code, notes, and snippets.

@LightGive
Created October 28, 2017 06:48
Show Gist options
  • Save LightGive/8acf80d9f432daef46bd291255fa200a to your computer and use it in GitHub Desktop.
Save LightGive/8acf80d9f432daef46bd291255fa200a to your computer and use it in GitHub Desktop.
初速を加えてから地面に落ちるまでの時間を計算するスクリプト
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 初速を加えてから地面に落ちるまでの時間を計算する
/// </summary>
public class Test4 : MonoBehaviour
{
//初速
[SerializeField]
private Vector3 v0;
//地面の座標
[SerializeField]
private float gp;
private Rigidbody rigid;
private bool isShot = false;
private float timeCnt = 0.0f;
private float stopTime = 0.0f;
void Start()
{
rigid = GetComponent<Rigidbody>();
if (!rigid)
{
rigid = gameObject.AddComponent<Rigidbody>();
}
rigid.isKinematic = true;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
var t1 = (v0.y + Mathf.Sqrt(Mathf.Pow(-v0.y, 2.0f) + (-2 * -Physics.gravity.y * (-transform.position.y + gp)))) / (-Physics.gravity.y);
var t2 = (v0.y - Mathf.Sqrt(Mathf.Pow(-v0.y, 2.0f) + (-2 * -Physics.gravity.y * (-transform.position.y + gp)))) / (-Physics.gravity.y);
Debug.Log("t1:" + t1.ToString("f3") + " t2:" + t2.ToString("f3"));
//秒数がNaNの時か秒数がマイナスの時は処理しない
if ((float.IsNaN(t1) && float.IsNaN(t2)) || (t1 < 0) && (t2 < 0))
return;
stopTime = (t1 > 0) ? t1 : t2;
rigid.isKinematic = false;
rigid.AddForce(v0, ForceMode.VelocityChange);
isShot = true;
timeCnt = 0.0f;
}
if (!isShot)
return;
timeCnt += Time.deltaTime;
if (timeCnt >= stopTime)
{
isShot = false;
Debug.Break();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment