How to generate a raycast on keydown and store what it hits as a variable
Hello and disclaimer: I am a novice.
Some basic information: my project is a 2D strategy game mimicking Shining Force 2. Movement is based on a grid, and the player and all NPCs occupy 1 grid space (32x32 tile). My goal is to use the WASD keys to generate a short raycast in the direction pressed (eg press up, ray goes up) and use the collision information to do a number of things:
1. Given that player movement is accomplished with 1 unit X/Y transforms, the collision will prevent further movement in the direction collided with. This simulates grid movement. 2. Use collisions to set NPC, door, treasure box, etc scripts to an active state, mimicking a context sensitive button. eg, if collision with NPC A is true, the player will press a button to cause the diologue of NPC A to appear, or if collison with treasure box A is true, the player will press a button to open the box.
Is this feasible? So far I have this:
Vector3 pos;
public float speed = 2.0f;
void Start()
{
pos = transform.position; // Take the current position
anim = GetComponent<Animator>();
}
void FixedUpdate()
{
//====RayCasts====//
RaycastHit2D hitup = Physics2D.Raycast(transform.position, Vector2.up, 1);
RaycastHit2D hitdown = Physics2D.Raycast(transform.position, Vector2.down, 1);
RaycastHit2D hitright = Physics2D.Raycast(transform.position, Vector2.right, 1);
RaycastHit2D hitleft = Physics2D.Raycast(transform.position, Vector2.left, 1);
//==Inputs==//
if (Input.GetKey(KeyCode.A) && transform.position == pos && hitleft.collider == null)
{ //(-1,0)
pos += Vector3.left * 1;// Add -1 to pos.x
}
if (Input.GetKey(KeyCode.D) && transform.position == pos && hitright.collider == null)
{ //(1,0)
pos += Vector3.right * 1;// Add 1 to pos.x
}
if (Input.GetKey(KeyCode.W) && transform.position == pos && hitup.collider == null)
{ //(0,1)
pos += Vector3.up * 1; // Add 1 to pos.y
}
if (Input.GetKey(KeyCode.S) && transform.position == pos && hitdown.collider == null)
{ //(0,-1)
pos += Vector3.down * 1;// Add -1 to pos.y
}
//The Current Position = Move To (the current position to the new position by the speed * Time.DeltaTime)
transform.position = Vector3.MoveTowards(transform.position, pos, speed); // Move there
This works very well to mimick the type of movement the 16 bit game had, it's basically perfect. However, I want the raycasts to only occur upon pressing one of the WASD keys and only in that direction, until another WASD key is pressed, while keeping the movement the same. How can I accomplish this?
if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.A) && transform.position == pos)
{
RaycastHit2D hitleft = Physics2D.Raycast(transform.position, Vector2.left, 1);
if (hitleft.collider == null) pos += Vector3.left * 1;
}
?