Align CharacterTo Wall Problem (254427)

Hey, I am trying to align my characters Y position to a wall.
so in this example, the lower capsule part should stick to the red area:
200287-ezgif-4-d3e62ba532.gif
here is my code:

using UnityEngine;
 
public class MoveTest : MonoBehaviour
{
    [SerializeField] Vector3 _direction;
    public Transform wall;
 
    void Update()
    {
        _direction.x = Input.GetAxis("Horizontal");
        _direction.z = Input.GetAxis("Vertical");
 
        UpdatePosition();
        UpdateRotation();
    }
    void UpdatePosition()
    {
   
        transform.position += wall.right * _direction.x * 0.1f;
        transform.position += wall.up * _direction.z * 0.1f;
    }
    void UpdateRotation()
    {
        var _targetRotation = Quaternion.FromToRotation(transform.up, -wall.forward) * transform.rotation;
        transform.rotation = _targetRotation;
    }
}

what do i have to do, to make get the Y of the character stay at the red wall, while still being able to move left and right/up down?

also note, that the red and white boxes are just there for showing the problem. Only the blue box will be there in the end. So raycasting down to the red cube wont be possible

2 Answers

2

You may be overthinking this… Assuming the wall itself doesn’t move, simply align your capsule to the wall and then move using transform.Translate, which only moves in local space. The WASD/Arrow keys won’t ever move away from the face of the wall.

However, since you’ve rotated the capsule, the keys don’t work as expected but just make your horizontal keys move vertically and vice versa as per the script below:

using UnityEngine;

public class TranTran : MonoBehaviour
{
    float speed = 10f;

    void Update()
    {
        float y = Input.GetAxisRaw("Horizontal");
        float x = Input.GetAxisRaw("Vertical");
        Vector3 direction = new Vector3(x, 0, -y).normalized;
        transform.Translate(direction * speed * Time.deltaTime);
    }
}

hey, thanks for your comment. sadly this is not working for my use case. the direction of the wall (wall.right & up) should define the input directions. not the local space or direction of the character. working fine, all thats missing is align the character up to the wall Z axis on update

Is there anything stopping you making the character a child object of the wall?