- Home /
How to move Sword using mouse only when space button is pressed.
How can i move the sword with the mouse only when the space button is pressed? So when you don't press the space button, moving the mouse will not make the sword move, but when you press the space button, when moving the mouse it will make sword move. PLEASE ANSWER WITH C# CODE (COMPLETE CODE)
Answer by ADiSiN · May 08, 2020 at 12:47 PM
Hi!
Basically, what you need to do is to track Space input with any variable, for example boolean and then, based on received information, apply sword movement logic when conditions are right.
Here is example when you hold Space and Transform sword will be locked to mouse position in world space with constant sword's Z position in world space.
public Camera cam;
public Transform sword;
bool is_Space;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
is_Space = true;
else if (Input.GetKeyUp(KeyCode.Space))
is_Space = false;
if (is_Space)
{
// Any implementation of sword movement
float zPos = cam.WorldToScreenPoint(sword.position).z;
Vector3 newPos = cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, zPos));
sword.position = newPos;
}
}
Your answer
Follow this Question
Related Questions
OnCollisionEnter Issue... 1 Answer
enable components from multiple objects 0 Answers
VR Sword tracking 1 Answer
Swinging a sword through code 3 Answers
Move Sword(GameObject) along a path with mouse with same speed 1 Answer