バネのチェーン|Unity5

バネのチェーン|Unity5

バネのチェーン|Unity5 : ZIPファイル(544kb)

C#

SpringChain.cs

using UnityEngine;
using System.Collections;

public class SpringChain : MonoBehaviour {
	GameObject[] balls;
	int numBalls = 5;
	float spring = 0.006f;
	float friction = 0.95f;
	float gravity = -0.007f;
	LineRenderer renderer;

	// Use this for initialization
	void Start () {
		balls = new GameObject[numBalls];
		for (int i = 0; i < balls.Length; i++) {
			GameObject ball = GameObject.Find ("ball");
			Vector2 pos = ball.transform.position;

			GameObject obj = Instantiate (ball, pos, ball.transform.rotation) as GameObject;
			balls [i] = obj;
		}
			
		renderer = gameObject.GetComponent<LineRenderer>();

		// 頂点の数
		renderer.SetVertexCount(numBalls+1);

		// 線の幅
		renderer.SetWidth(0.05f, 0.05f);
		renderer.material = new Material (Shader.Find ("Particles/Additive"));
	}
	
	// Update is called once per frame
	void Update () {
		Vector2 tap = Camera.main.ScreenToWorldPoint (Input.mousePosition);
		float mouseX = tap.x;
		float mouseY = tap.y;

		renderer.SetPosition(0, new Vector2(mouseX, mouseY));
		renderer.SetPosition(1, new Vector2(balls[0].transform.position.x, balls[0].transform.position.y));

		moveBall (balls [0], mouseX, mouseY);

		for (int i = 1; i < numBalls; i++) {
			GameObject ballA = balls [i - 1];
			GameObject ballB = balls [i];
			moveBall (ballB, ballA.transform.position.x, ballA.transform.position.y);
			renderer.SetPosition (i+1, new Vector2 (ballB.transform.position.x, ballB.transform.position.y));
		}
	}

	void moveBall(GameObject ball, float targetX, float targetY)
	{
		Vector2 v = ball.transform.position;
		ball.GetComponent<Ball>().vx += (targetX - v.x) * spring;
		ball.GetComponent<Ball>().vy += (targetY - v.y) * spring;
		ball.GetComponent<Ball>().vy += gravity;
		ball.GetComponent<Ball>().vx *= friction;
		ball.GetComponent<Ball>().vy *= friction;
		v.x += ball.GetComponent<Ball>().vx;
		v.y += ball.GetComponent<Ball>().vy;
		ball.transform.position = v;
	}
}

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です