I would like to push and pull the cubes in one axis (x or z).
I don’t know how to aim the object. I think I should use
gameObject.transform.position.x += something;
I’m not sure if you are using Transforms or a Rigidbody. Assuming you are using a Rigidbody, then for your object:
Add a Rigidbody component
Set the 'isKinematic flag to true
Attach the following script
In the inspector, set the ‘relativeOpenPos’ variable.
Set the speed variable
'relativeOpenPos is the direction and distance to move the object. So if open is 1.5 units to the right, you would set it to (1.5, 0,0). If open is two units forward, then you would set it to (0,0,2).
#pragma strict
public var relativeOpenPos = Vector3(1,0,0);
public var speed = 1.0f;
private var posOpen;
private var posClose;
private var posDest;
private var open = false;
function Start() {
posClose = transform.position;
posOpen = transform.position + relativeOpenPos;
posDest = posClose;
}
function Update() {
var pos = Vector3.MoveTowards(transform.position, posDest, Time.deltaTime * speed);
rigidbody.MovePosition(pos);
}
function OpenClose() {
open = !open;
posDest = open ? posOpen : posClose;
}
Here is the code that can trigger open and closing on a mouse click. It assumes that the object is tagged ‘PushPull’.
#pragma strict
function Update() {
var hit : RaycastHit;
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Input.GetMouseButtonDown(0)) {
if (Physics.Raycast(ray, hit) && (hit.collider.tag == "PushPull")) {
hit.collider.GetComponent(PushPull).OpenClose();
}
}
}
Note if you are not using a Rigidbody, you can change line 19 to:
Hello everybody, robertbu’s script works very well and I am very glad about it.
I’m looking now for other push/pull script which could be used for non static objects like above but something like force to move (addForce) forward and backward the objects.
Player have ability to push from him and pull to him objects (here he is pulling cube with other force - in previous video he is pulling objects like weapons / equipment / bodies).
I think I should also use rigidbody here. Could someone help?
As I assume here “is kinematic” must be turned off?
Also I think we can use and modify the robertbu’s previous script.