Question by
astein3535 · Apr 18, 2019 at 08:10 AM ·
2dobjectsmousepositionmoveposition
Object won't move with mouse
I'm starting to try out Unity for the first time today and have been doing a few tutorials. I've followed all of the steps correctly, but now I'm stuck. I basically want to move an object on the x-axis and have it follow the cursor. Currently, it doesn't do anything. Any help to get me back on the right track would be appreciated. This is the code I have:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HatController : MonoBehaviour
{
public Camera cam;
// Start is called before the first frame update
void Start()
{
if (cam == null)
cam = Camera.main;
}
// Update is called once per physics timestep
void FixedUpdate()
{
Vector3 rawPosition = cam.ScreenToWorldPoint(Input.mousePosition);
Vector3 targetPosition = new Vector3(rawPosition.x, 0.0f, 0.0f);
GetComponent<Rigidbody2D>().MovePosition(targetPosition);
}
}
Comment
Answer by Poi7ioN · Apr 19, 2019 at 03:08 PM
In the update function you can try this..
void update()
{
float mouseposition = Input.mousePosition.x / Screen.width * screenWidthInUnits; // this is the unity units from left side of screen to right so make sure you get that right.
vector2 ObjectWantToMove = new Vector2(mouseposition , transform.position.y); // change x axis and keep the y axis same for the object
transform.position = ObjectWantToMove;
}
// This is what i did for my Arkanoid game to move paddle along with mouse. Hope it helps