Unity:C#スクリプト(Ball)の作成
ProjectエリアのCreateのメニューから、「C# Script」を選択します。
Assetsに「C# Script」が作成されるので名前を「NewBehaviourScript」→「Ball」にします。
※名前の変更が後回しになると、クラス名が「NewBehaviourScript 」となってしまうので
クラス名も「Ball」変更にする必要が出てきます。
using UnityEngine;
using System.Collections;
public class Ball : MonoBehaviour {
// Speed to be modified in the Inspector
public float speed = 100.0f;
void Start() {
// Give the ball some initial movement direction
rigidbody2D.velocity = Vector2.up * speed;
}
float hitFactor(Vector2 ballPos, Vector2 racketPos, float racketWidth) {
// ascii art:
//
// 1 -0.5 0 0.5 1 <- x value
// =================== <- racket
//
return (ballPos.x - racketPos.x) / racketWidth;
}
void OnCollisionEnter2D(Collision2D col) {
// Hit the Racket?
if (col.gameObject.name == "racket") {
// Calculate hit Factor
float x=hitFactor(transform.position,
col.transform.position,
((BoxCollider2D)col.collider).size.x);
/ / Calculate direction, set length to 1
Vector2 dir = new Vector2(x, 1).normalized;
// Set Velocity with dir * speed
rigidbody2D.velocity = dir * speed;
}
}
}