- Home /
Destroying game object next to player
Hi i am trying to create a script that destroys a game object that is directly next to my player with a keyboard command.
My game has a 2d perspective and a third person view with the camera locked to following my player who is controlled by a character controller ( i guess similar to old mario games) what i am aiming for is - by pushing a direction (left, up, right or down) and the "k" key you destroy the game object adjacent to the player in that direction
the current script i have is destroying game objects when i click but i can't figure out how to get it to work the way i want. I have tried changing the input method to (for eg) "K" but it still has no effect
the code i have is
function Update(){
if (Input.GetMouseButtonDown(1)){
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var hit: RaycastHit;
if (Physics.Raycast(ray, hit)){
Destroy(hit.transform.gameObject);
}
}
}
Any help would be greatly appriciated
This is an interesting idea, but the question needs alot more information to get help.
Is this 2D or 3D? How is the player character viewed? How does the player control the player and camera? How is it shown where the player is choosing to dig?
Your destroy example suggests you are using a mouse to choose what to dig, with the question being how do I choose an object immediately around the player character.
Your text suggests you want to have the player character dig directly in front on a certain keypress, down on another keypress, left with another etc. Please clarify and edit the question. A screenshot of the player character in the environment as seen while playing would be great.
Answer by refardeon · Sep 25, 2012 at 10:35 AM
Can't you use the player characters location as source for your ray? Something like:
if (rightButton) {
var ray = new Ray ( player.transform.position, Vector3.right, distance);
} else if (downButton) {
var ray = new Ray ( player.transform.position, -Vector3.up, distance);
}
// Same for left (-Vector3.right) and up (Vector3.up)
var hit: RaycastHit;
if (Physics.Raycast(ray, hit)){
Destroy(hit.transform.gameObject);
}
This is very untested, but something along these lines should work.
Your answer
![](https://koobas.hobune.stream/wayback/20220613081345im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Script to destroy object 1 Answer
OnTriggerEnter not working 1 Answer
destroy parent of script 1 Answer
Destruct gameobject by call from another script 1 Answer
Destroyable terrain? 2 Answers