Hi Nina,
OK this works perfectly. In fact, it works better than my first project where I the paddle didn’t follow the mouse properly.
Update: I don’t know how to insert mathf.clamp so my paddle goes out of the screen. My code is below now. As following the above, it doesn’t properly follow what the tutorial showed. So how do we fix this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Paddle : MonoBehaviour
{
/*
* 1440 * 1080
[SerializeField] float screenWidthInUnits = 50f;
[SerializeField] float minX = -14f;
[SerializeField] float maxX = 6f;
*/
/*
[SerializeField] float minX = 1f;
[SerializeField] float maxX = 7f;
*/
[SerializeField] Camera Camera; // DRAG YOUR CAMERA;
[SerializeField] float screenWidthInUnits = 50f;
[SerializeField] float minX = 1.2f;
[SerializeField] float maxX = 14.8f;
// Start is called before the first frame update
void Start()
{
if (!Camera) Camera = FindObjectOfType<Camera>();
}
// Update is called once per frame
void Update()
{
//Debug.Log(Input.mousePosition.x / Screen.width);
/*
float mousePosInUnits = Input.mousePosition.x / Screen.width * screenWidthInUnits;
Vector2 paddlePos = new Vector2(transform.position.x, transform.position.y);
paddlePos.x = Mathf.Clamp(mousePosInUnits, minX, maxX);
transform.position = paddlePos;
*/
MovePaddle();
}
void MovePaddle()
{
Vector3 newPos = Camera.ScreenToWorldPoint(Input.mousePosition);
newPos.y = transform.position.y; newPos.z = transform.position.z;
transform.position = newPos;
}
}