Autonomous underwater vehicles (AUVs) have been widely used in ocean missions. When they fail in the ocean, it is important to predict their trajectory. Existing methods rely heavily on historical trajectory data while overlooking the influence of the ocean environment on an AUV’s trajectory. At the same time, these methods fail to use the dependency between variables in the trajectory. To address these challenges, this paper proposes an AUV trajectory prediction model known as the nonlinear Kepler optimization algorithm–bidirectional long short-term memory–time-variable attention (NKOA-BiLSTM-TVA) model. This paper introduces opposition-based learning during the initialization process of the KOA and improves the algorithm by incorporating a nonlinear factor into the planet position update process. We designed an attention mechanism layer that spans both time and variable dimensions, called TVA. TVA can extract features from both the time and variable dimensions of the trajectory and use the dependency between trajectory variables to predict the trajectory. First, the model uses a convolutional neural network (CNN) to extract spatial features from the trajectory. Next, it combines a BiLSTM network with TVA to predict the AUV’s trajectory. Finally, the improved NKOA is used to optimize the model’s hyperparameters. Experimental results show that the NKOA-BiLSTM-TVA model has an excellent parameter optimization effect and higher prediction accuracy in AUV trajectory prediction tasks. It also achieves excellent results in ship trajectory prediction.