Grabbing Object Trouble
So what I’m trying to do right now is have my player character grab and push/pull objects around (think the crate pushing found in some platformer games).
The idea being that when Fire2 (right mouse button) is pressed, it will pick up the object.
I’ve got a trigger volume called “Grabber” that’s following the player character’s X and Y positions (I deliberately chose not to parent Grabber directly to the player character and instead via scripting because this gives me greater control over the Grabber in case if something bad happens). The tag that the Grabber is specifically looking for is “Object”. It’s set up so that if the object with the correct tag enters the Grabber, it will return the statement in a different script, ObjectEnter, as True. If that conditional is fulfilled in addition to Fire2 being pressed, it should then activate the “grabbing” function.
What’s supposed to happen is that after the Object is found via the GameObject.FindTag statement, and then the Object should change position to be identical to Grabber’s position (meaning that ideally, it should be held in the center of the Grabber). Unfortunately, that hasn’t happened.
It could be because I’m initializing the variables in the wrong place (as I was previously getting thrown errors when I did try to initialize them in what I thought was the normal place: at the top of the script before the Start function), or there could be an extra step I’m missing.
var grabberCube : GameObject;
var player : GameObject;
var grabberPos : Vector3;
var grabberXPos : float;
var grabberXAdj : float = 0.0;
var object : GameObject;
var objectPos : Vector3;
var otherObjPos : Vector3;
function Start () {
}
function Update () {
grabberPos = grabberCube.transform.position;
grabberXPos = grabberCube.transform.position.x;
grabberCube.transform.position.x = player.transform.position.x + grabberXAdj;
grabberCube.transform.position.y = player.transform.position.y;
//objectPos = object.transform.position;
//print(objectPos);
if(cameraMovement.moveRight == true){
grabberXAdj = 1.3;
}
if(cameraMovement.moveLeft == true){
grabberXAdj = -1.3;
}
if(Input.GetButton("Fire2") && cameraMovement.objectEnter == true){
grabbing();
}
if(Input.GetButton("Fire2") && cameraMovement.objectEnter != true){
print("Nothing to grab");
}
}
function grabbing(){
object = GameObject.FindWithTag("Object");
objectPos = object.transform.position;
objectPos = grabberPos;
print(objectPos);
print("Grabbed!");
}
Your answer
Follow this Question
Related Questions
2d touch not working 0 Answers
How Do I Destroy All Objects At a Given Location? 2 Answers
Setting transform.position of the Oculus Player Controller causes it to teleport away 1 Answer
How to fix (NullReferenceException: Object reference not set to an instance of an object) in my case 0 Answers
Do touch on point where ray hits 0 Answers