making movement stop at object collision
so in my game i have made it so that my character moves by getting the "Input.GetAxis" for both vertical and horizontal and then transforming its current position based on that (and a variable that determines speed). my problem right now is that i cant figure out how to get the player to "stop" at walls and other objects. i thought about checking where the collision is and then make it stop being able to go in that direction but so far i can't figure out how to without either stopping the vertical/ horizontal movement entierly or making it impossible to move diagonaly. i feel like there is some easy way that i don't know about but i can't find it. here's my script thanks for the help
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerScript : MonoBehaviour
{
[SerializeField] public MousePoint mousePoint;
[SerializeField] CanMove canMove;
[SerializeField] private float speed = 0.001f;
[SerializeField] public InventoryMenu inventoryMenu;
public float horizontalInput;
public float verticalInput;
private Vector3 playerPos;
private float tempSpeed;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (canMove.move)
{
//defyning stuff
playerPos = gameObject.transform.position;
tempSpeed = speed;
//movement based on vertical and horizontal
verticalInput = Input.GetAxis("Vertical");
horizontalInput = Input.GetAxis("Horizontal");
gameObject.transform.position = new Vector3(playerPos.x + (horizontalInput * tempSpeed), playerPos.y, playerPos.z + (verticalInput * tempSpeed));
//rotate towards "MousePoint"
float angle = AngleBetweenPoints(transform.position, mousePoint.transform.position);
transform.rotation = Quaternion.Euler(new Vector3(0f, angle + 10f, 0f));
}
}
private void OnTriggerStay(Collider other)
{
//inventoryMenu.SetInteractText("F to Examine");
}
float AngleBetweenPoints(Vector3 a, Vector3 b)
{
return Mathf.Atan2(b.x - a.x, b.z - a.z) * Mathf.Rad2Deg;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613045402im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Movement causing infinite loops in OnTriggerEnter and OnTriggerExit. 1 Answer
How to make rigidbody not effect movement while still using it for collisions? 0 Answers
How to make my moving object (in game) stop once it collides 1 Answer
collision is making its own vector 1 Answer
How do I count Hits ?? 2 Answers