-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathPhysicsPickup.cs
More file actions
98 lines (77 loc) · 2.42 KB
/
PhysicsPickup.cs
File metadata and controls
98 lines (77 loc) · 2.42 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PhysicsPickup : MonoBehaviour
{
//distance from the camera the item is carried
public float dist = 2.5f;
//the object being held
private GameObject curObject;
private Rigidbody curBody;
//the rotation of the curObject at pickup relative to the camera
private Quaternion relRot;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
//on mouse click, either pickup or drop an item
if(Input.GetMouseButtonDown(0))
{
if(curObject == null)
{
PickupItem();
}
else
{
DropItem();
}
}
}
void FixedUpdate()
{
if(curObject != null)
{
//keep the object in front of the camera
ReposObject();
}
}
//calculates the new rotation and position of the curObject
void ReposObject()
{
//calculate the target position and rotation of the curbody
Vector3 targetPos = transform.position + transform.forward * dist;
Quaternion targetRot = transform.rotation * relRot;
//interpolate to the target position using velocity
curBody.velocity = (targetPos - curBody.position) * 10;
//keep the relative rotation the same
curBody.rotation = targetRot;
//no spinning around
curBody.angularVelocity = Vector3.zero;
}
//attempts to pick up an item straigth ahead
void PickupItem()
{
//raycast to find an item
RaycastHit hitInfo;
Physics.Raycast(transform.position, transform.forward, out hitInfo, 5f);
if(hitInfo.rigidbody == null)
return;
curBody = hitInfo.rigidbody;
curBody.useGravity = false;
curObject = hitInfo.rigidbody.gameObject;
//hack w/ parenting & unparenting to get the relative rotation
curObject.transform.parent = transform;
relRot = curObject.transform.localRotation;
curObject.transform.parent = null;
}
//drops the current item
void DropItem()
{
curBody.useGravity = true;
curBody = null;
curObject = null;
}
}