0

I want to figure out how to make this gameobject follow another game object on the x axis only. here is all I have so far.

public Transform mouse; 
private Vector3 offset; 

// Start is called before the first frame update
void Start()
{
    
}

// Update is called once per frame
void Update()
{
    
}


void follow()
{
    transform.position.x = mouse.position.x;
}
Cottontail
  • 13
  • 2
  • in your `Update()` method, call `follow()`. – Geeky Quentin May 26 '22 at 00:39
  • `Vector3` variables, like `.position`, are value types. You can modify `position.x`, but you can't modify `transform.position.x`. See https://stackoverflow.com/questions/7212618/unable-to-modify-struct-members – 3Dave May 26 '22 at 01:00

1 Answers1

0

You almost had it! I might do a bad job explaining this but the reason that doesn't work is because a vector3 has readonly properties, to change it you have to create a new one, so there may be a better way but here's what I always used.

new Vector3(mouse.x, transform.position.y, transform.position.z)

Cheers

SupaMaggie70 b
  • 322
  • 3
  • 8
  • There are `MoveTowards` and `Lerp` so you don't have to do that. https://answers.unity.com/questions/56251/make-object-move-tofollow-another-object-plus-turn.html – Xiang Wei Huang May 26 '22 at 00:50
  • @XiangWeiHuang `MoveTowards`, `Lerp`, etc. are static methods. They're not valid on an instance (and wouldn't modify it if they were). You'd still have to generate a new Vector3. – 3Dave May 26 '22 at 00:56
  • Sorry for being unclear. The main reason I suggested those is because you don't have to control directly the `x`, `y`, `z`, rather, tell only two positions, length per step and let the function make the change, it also supports smooth movements rather than snap right onto the new position. But... This did make me realize that the OP's question is moving on X-Axis only, which I think still needs a new Vector3 indeed. My apologizes. – Xiang Wei Huang May 26 '22 at 02:43