-
Notifications
You must be signed in to change notification settings - Fork 0
/
BallControlbyMouse.cs
66 lines (53 loc) · 2.15 KB
/
BallControlbyMouse.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
using System;
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
using System.Collections.Generic;
public class BallControlbyMouse : MonoBehaviour
{
public float MovePower = 100f;
public float TopSpeed = 20.0f;
private Vector3 move; //vector starts from the current ball position and to the location of mouse click
private float _InertiaAngle; //angle between current move direction -velocity- and the applied force direction
private Vector3 Velocity; //Current move direction of ball
private Rigidbody _Rigidbody;
private void Awake()
{
_Rigidbody = GetComponent<Rigidbody>();
}
private void FixedUpdate()
{
if (Input.GetMouseButton(0)) //when mouse is clicked get the direction
{
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit = new RaycastHit();
if (Physics.Raycast(ray, out hit))
{
move = hit.point - transform.position;
move.y = 0;
Move(move.normalized);
}
}
if (Velocity.sqrMagnitude > TopSpeed * TopSpeed) //maintain top speed
Velocity = Velocity.normalized * TopSpeed;
}
public void Move(Vector3 moveDirection) //how to move the ball depending on angle between click and velocity vectors
{
Velocity = _Rigidbody.velocity.normalized;
_InertiaAngle = Vector3.Angle(moveDirection, Velocity);
if (_InertiaAngle > 115.0f)
{
_Rigidbody.velocity *= 0.01f;
}
else if (_InertiaAngle > 55.0f)
{
_Rigidbody.AddForce((-Velocity + moveDirection) * MovePower * 7, ForceMode.Acceleration);
_Rigidbody.AddForce(-moveDirection * MovePower * 3, ForceMode.Acceleration);
}
else
{
_Rigidbody.AddForce((-Velocity + moveDirection) * MovePower * 7, ForceMode.Acceleration);
}
_Rigidbody.AddForce(moveDirection * MovePower, ForceMode.Acceleration);
}
}